Tuesday, June 13, 2017

25. 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.
k is a positive integer and is less than or equal to the length of the linked 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:

For example if the linked list is 1 - > 2 -> 3 -> 4 and k = 2.

In order to flip, we need to have 1's previous node.

Therefore we use a dummy node as the head.

d -> 1 - > 2 -> 3 -> 4

The flip is the classic reverse linked list method.

We use a for loop to reverse each pair k times.

After flipping, we connect 1 to 3 and make 1 the new head.

d -> 2 -> 1 -> 3 -> 4

For each flip, we first check if there exists k nodes. If not, we simply return null.



Code:


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
        while (head != null) {
            head = reverseK(head, k);
        }
        return dummy.next;
    }
    
    public ListNode reverseK(ListNode head, int k) {
        ListNode curr = head.next;
        for (int i = 0; i < k; i++) {
            if (curr == null) {
                return null;
            }
            curr = curr.next;
        }
        
        ListNode prev = null;
        curr = head.next;
        for (int i = 0; i < k; i++) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        
        ListNode newHead = head.next;
        newHead.next = curr;
        head.next = prev;
        return newHead;
    }
}