Reverse Nodes in k-Group
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example, Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
https://leetcode.com/problems/reverse-nodes-in-k-group/
Solution:
tricky part: break the link into piece of size k and reverse then assembly
dont forget the last part
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || k <= 1) {
return head;
}
int count = 0;
ListNode dummyHead = new ListNode(0);
ListNode n = dummyHead;
ListNode currHead = head;
while (head != null) {
count++;
if (count == k) {
ListNode t = head.next;
head.next = null; // break the link first
n.next = reverse(currHead);
n = currHead;
currHead = t;
head = t;
count = 0;
} else {
head = head.next;
}
}
// the last part with size < k
if (count < k) {
n.next = currHead;
}
return dummyHead.next;
}
public ListNode reverse(ListNode head) {
ListNode dummyHead = new ListNode(0);
while (head != null) {
ListNode n = head.next;
head.next = dummyHead.next;
dummyHead.next = head;
head = n;
}
return dummyHead.next;
}
}