Reverse Nodes in k-Group

By | September 2, 2016
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

leetcode 25.

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

Solution. Should pay attention if we do 1->2->3->4->5->6->7->8->9->10, k = 4. Then the result should be: 4->3->2->1->8->7->6->5->9->10. We don’t swap the 3rd group, which is last 2 elements.

So the idea is that we swap each k elements group. This is a general process described in this Reverse Linked List II problem. A front node should be in the front to monitor if current group is reversible.

In below example, it reverse each k elements group. When front is null, we stop reversing current group.

reversekgroup2

public static ListNode reverseKGroup(ListNode head, int k) {
    ListNode dummy = new ListNode(0), front = head;
    dummy.next = head;
    head = dummy;
    for (int i = 1; i < k && front != null; i++) {
        front = front.next;
    }
    while (front != null) {
        ListNode tail = head.next, curr = tail.next;
        for (int i = 1; i < k; i++) {
            front = front == null ? null : front.next;
            tail.next = curr.next;
            curr.next = head.next;
            head.next = curr;
            curr = tail.next;
        }
        front = front == null ? null : front.next;
        head = tail;
    }
    return dummy.next;
}

Check my code on github.