public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(0, 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;
pre.next = reverseList(start);
start.next = next;
pre = start;
end = pre;
}
return dummy.next;
}
public ListNode reverseList(ListNode head){
if(head == null || head.next == null) return head;
ListNode nh = reverseList(head.next);
head.next.next = head;
head.next = null;
return nh;
}
进阶提问:最后一组也反转呢?(easy)
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(0, head);
ListNode pre = dummy;
ListNode end = dummy;
while(end.next!=null){
//唯一区别在于判断end.next != null,这样会遍历到最后一个节点,然后后续同前面的k个一组的节点一样
for(int i=0;i<k && end.next !=null;i++) end= end.next;
// if(end == null) break;
ListNode next = end.next;
ListNode start = pre.next;
end.next = null;
pre.next = reverseList(start);
start.next = next;
pre = start;
end = pre;
}
return dummy.next;
}
private ListNode reverseList(ListNode head){
if(head == null||head.next==null) return head;
ListNode nh = reverseList(head.next);
head.next.next = head;
head.next = null;
return nh;
}
}
反转链表的递归版本。。。麻了
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null || head.next == null) return head;
ListNode tail = head;
for(int i=0;i<k;i++){
if(tail == null){
return head;
}
tail = tail.next;
}
ListNode nh = reverseList(head, tail);
head.next = reverseKGroup(tail, k);
return nh;
}
public ListNode reverseList(ListNode head, ListNode tail){
if(head.next == tail) return head;
ListNode nh = reverseList(head.next, tail);
head.next.next = head;
head.next = null;
return nh;
}