LeetCode - Reverse Nodes in k-Group

1 minute read

Problem description

description

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.

Example:

1
2
3
4
5
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

Note:

  • Only constant extra memory is allowed.
  • You may not alter the values in the list’s nodes, only nodes itself may be changed.

Analysis

Basic idea is to divide the LinkedList into fragments with K element virtually. We can use two pointer to do this. And then we reverse the fragment one by one.

Here’s the code:

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
public class ReverseNodesinkGroup {
  public ListNode reverseKGroup(ListNode head, int k) {
    ListNode dummy = new ListNode(0);
    dummy.next = head;

    ListNode p1 = dummy, p2 = head;

    while (p2 != null) {
      int i = 0;
      while (i < k) {
        if (p2 != null) {
          p2 = p2.next;
          i++;
        } else {
          return dummy.next;
        }
      }

      ListNode nextP1 = p1.next;
      reverseK(p1, p2);
      p1 = nextP1;
    }

    return dummy.next;
  }

  void reverseK(ListNode pre, ListNode end) {
    ListNode p = pre.next;
    while (p.next != end) {
      ListNode next = p.next;
      p.next = p.next.next;
      next.next = pre.next;
      pre.next = next;
    }
  }
}

When we do reverse, we must make sure that the node before the fragment and the node after it don’t change, so the parameter should be pre and end.

What to improve

  • forget to consider the p2 = null case but luckily it works.