链接: link
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
/**
prev: 用来头插
tmp: 每次头插前记录一下,好进行下一次头插
*/
public ListNode reverseKGroup(ListNode head, int k) {
ListNode cur = head;
int n = 0;
while(cur != null){
cur = cur.next;
n++;
}
n = n / k;//统计需要翻转链表几次
cur = head;
ListNode newHead = new ListNode(0);
ListNode prev = newHead;
for(int i = 0; i < n; i++){
ListNode tmp = cur;
for(int j = 0; j < k; j++){
ListNode next = cur.next;
cur.next = prev.next;
prev.next = cur;
cur = next;
}
prev = tmp;
}
//把后面不需要逆序的连接上
prev.next = cur;
return newHead.next;
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有