25. Reverse Nodes in k-Group

Given the head of a linked list, reverse the nodes of the list k at a time, and return the 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 list’s nodes, only nodes themselves may be changed.

采用直接更改节点的方法可以使用O(1)的空间完成操作。

递归,DFS搜索,首先初始化一个哨兵节点。
将哨兵节点记录为first,下一个节点记录为second。

将first与second传入递归方法。
向下递归下一个节点,并将长度k-1。
当长度k等于1时,则递归到当前所需的栈底。将当前节点指向上一个节点,并将当前节点记录为last,下一个节点记录为next,返回true。
当curr为null时,返回false。

当递归返回为true时(即剩余的链表有k个节点以供翻转),上级的节点们都指向其前一个节点。当返回到的栈顶(即k等于最开始的值)时,将first指向last,将second指向next。

继续向下递归first与second。

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
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* 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 {
int K;
ListNode next;
ListNode prev;
ListNode last;
ListNode first;
ListNode second;
public ListNode reverseKGroup(ListNode head, int k) {
if(k == 1) return head;

K = k;
ListNode dummy = new ListNode(0);
dummy.next = head;
prev = dummy;
next = null;
last = null;
first = prev;
second = prev.next;

reverse(prev, dummy.next, k);

return dummy.next;
}

private boolean reverse(ListNode prev, ListNode curr, int k){
if(curr == null) return false;
if(k == 1){
last = curr;
next = curr.next;
curr.next = prev;
return true;
}

if( reverse(curr, curr.next, k-1) ){
curr.next = prev;
if(k == K){
first.next = last;
second.next = next;
first = curr;
second = curr.next;

reverse(first, second, k);
}
return true;
}
return false;
}

private void print(ListNode root){
while(root != null){
root = root.next;
}
}
}
Author

Xander

Posted on

2022-04-28

Updated on

2022-04-28

Licensed under

Comments