Post

Reverse Nodes in k-Group

LeetCode https://leetcode.cn/problems/reverse-nodes-in-k-group/

Recursive

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
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode kth = head;
        int cnt = 1;
        while (kth != null && cnt < k) {
            cnt++;
            kth = kth.next;
        }
        if (kth == null) {
            return head;
        }
        ListNode nextKth = kth.next;
        ListNode prev = null, curr = head;
        while (curr != nextKth) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        head.next = reverseKGroup(nextKth, k);
        return kth;
    }
}

Complexity

  • Time = O(n)
  • Space = O(1)

Iterative

  • iterative method
This post is licensed under CC BY 4.0 by the author.