class Solution {
public ListNode cur;
public ListNode reverseKGroup(ListNode head, int k) {
cur = head;
ListNode pre, ans;
ans = null;
pre = null;
while(cur!=null){
head = cur;
ListNode t = reverse(cur, k);
if(pre!=null) pre.next = t;
else ans = t==null? cur: t;
if(ans==null) return head;
if(t==null) pre.next = head;
pre = head;
}
return ans;
}
public ListNode reverse(ListNode head, int k){
if(head==null||(head.next==null&&k>1)) return cur = null;
if(k==1){
cur = head.next;
return head;
}
ListNode t = reverse(head.next, k-1);
if(t!=null){
head.next.next = head;
head.next = null;
}
return t;
}
}
正常思路
记住pre start end 三点就可以了
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dumy = new ListNode(0);
dumy.next = head;
ListNode pre, end, start;
pre = dumy;
end = dumy;
while(end!=null){
for(int i=0; i<k&&end!=null; i++) end = end.next;
if(end==null) break;
ListNode next = end.next;
start = pre.next;
reverse(start, k);
pre.next = end;
pre = start;
pre.next = next;
end = pre;
}
return dumy.next;
}
public void reverse(ListNode start, int k){
ListNode pre, cur, next;
pre = null;
cur = start;
for(int i=0; i<k; i++){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
}
}
这个递归我没看懂,,可以解释一下吗