链接
题目描述
思路
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
ListNode end = dummy;
while(end.next != null){
for(int i = 0; i < k && end != null; i++){
end = end.next;
}
if(end == null){
break;
}
ListNode start = pre.next;
ListNode next = end.next;
end.next = null;//为了方便reverse函数
pre.next = reverse(start);
start.next = next;
pre = start;
end = start;
}
return dummy.next;
}
//反转链表
private ListNode reverse(ListNode start){
ListNode pre = null;
ListNode cur = start;
while(cur != null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}