Home LeetCode. 25. Reverse Nodes in k-Group
Post
Cancel

LeetCode. 25. Reverse Nodes in k-Group

image

[Link] https://leetcode.com/problems/reverse-nodes-in-k-group/


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
/**
 * 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 curNode = head, tailNode = null, headNode = null, node = curNode;
      if(k == 1) return head;

      loop:
      while(curNode != null) {
        node = curNode;
        ListNode tempHead = node;
        for(int i = 0; i < k - 1; i++) {
          node = node.next;
          if(node == null) break loop;
        }
        node = curNode.next;
        for(int i = 0; i < k - 1; i++) {
          ListNode nextNode = node.next;
          node.next = tempHead;
          tempHead = node;
          if(i != k - 2) node = nextNode;
          else {
            if(tailNode != null) tailNode.next = tempHead;
            else headNode = tempHead;
            tailNode = curNode;
            curNode = nextNode;
          }
        }

      }
      tailNode.next = curNode;
      return headNode;
    }
}
This post is licensed under CC BY 4.0 by the author.