LeetCode025 Reverse Nodes in k-Group
a classic one.
Two Notes:
Only constant extra memory is allowed.
You may not alter the values in the list’s nodes, only nodes itself may be changed.
although I’ve met thing problem many times, still can’t solve it.
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null) return null;
if(k == 0 || k== 1) return head;
ListNode p = head;
ListNode ktail = null;
ListNode new_head = null;
while (p != null) {
int count = 0; //k chunk counter
p = head;
while (count < k && p != null) {
p = p.next;
count++;
}
if (count == k) {
ListNode revHead = reverseLinkedList(head, k); //new head
if (new_head == null) new_head = revHead; //we only update new_head once, because we need to preserve the head.
if (ktail != null) ktail.next = revHead;
ktail = head; //ktail moves to the tail of sorted part
head = p; //and head move to the head of unsorted part
}
}
//if the remaining part is not enough for k, then we just attached the remaining linkedlist
if (ktail != null) {
ktail.next = head;
}
return new_head;
}
private ListNode reverseLinkedList(ListNode head, int k) { //we need to use this method to reverse k nodes of the given linkedlist
ListNode new_head = null; //create a new linkedlist to store reversed current linkedlist
ListNode p = head;
while (k > 0) {
ListNode next_node = p.next;
p.next = new_head;
new_head = p;
p = next_node;
k--;
}
return new_head; //return the new created linkedlist's head
}
}

浙公网安备 33010602011771号