[LeetCode] 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

Thought process:
Iterate through the linked list. Use two pointers to reverse k nodes at a time.

Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode left1 = dummy;
        ListNode left2 = head;
        ListNode right1 = head;
        ListNode right2 = head;
        
        while (right2 != null) {
            int i = 1;
            while (i < k && right1 != null) {
                right1 = right1.next;
                i++;
            }
            if (right1 == null) {
                return dummy.next;
            }
            
            right2 = right1.next;
            reverse(left1, left2, right1, right2);
            left1 = left2;
            left2 = right2;
            right1 = right2;
        }
        return dummy.next;
    }
    
    private void reverse(ListNode left1, ListNode left2, ListNode right1, ListNode right2) {
        ListNode previous = left1;
        ListNode current = left2;
        
        while (current != right2) {
            ListNode next = current.next;
            current.next = previous;
            previous = current;
            current = next;
        }
        
        left1.next = right1;
        left2.next = right2;
    }
}

Time complexity: O(n).

Comments

Popular posts from this blog

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee