25. K 个一组翻转链表(困难)

1,问题描述

25. K 个一组翻转链表

尝试过

难度(困难),感觉其实并不困难

提示:

给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。

k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。

示例 1:

img

1
2
输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]

示例 2:

img

1
2
输入:head = [1,2,3,4,5], k = 3
输出:[3,2,1,4,5]

提示:

  • 链表中的节点数目为 n
  • 1 <= k <= n <= 5000
  • 0 <= Node.val <= 1000

**进阶:**你可以设计一个只用 O(1) 额外内存空间的算法解决此问题吗?

2,思考过程

​ 符合要求:直接遍历,依次反转、重连即可

​ 也可以直接用空间换时间,使用一个hashMap直接解决战斗,但是空间复杂度O(n)

​ 本质:复杂问题拆分成多个简单问题的组合

3,代码处理

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
import support.ListNode;

public class _25K个一组翻转链表 {

// 感觉与之前的反转链表可以一起做
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || head.next == null || k == 1) {
return head;
}

ListNode next = null;
int counter = 0;

ListNode headNew = new ListNode();
headNew.next = head;
ListNode headBefore = headNew;

ListNode tail = headNew;
while (tail != null) {
if (counter == k) {
next = tail.next;// 下个循环的head节点的缓存
tail.next = null;// 截断链表
reverseList(head);// 链表反转

headBefore.next = tail;// 链表重连
headBefore = head;// 更新head前一个节点

head.next = next;// 链表重连
head = head.next;
tail = head;
counter = 1;
} else {
counter++;
tail = tail.next;
}
}
return headNew.next;
}

public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}

public static void main(String[] args) {
_25K个一组翻转链表 kGroup = new _25K个一组翻转链表();
ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5, new ListNode(6, new ListNode(7, new ListNode(8, new ListNode(9, new ListNode(10))))))))));
// ListNode head = new ListNode(1, new ListNode(2));
ListNode listNode = kGroup.reverseKGroup(head, 3);
while (listNode != null) {
System.out.println(listNode.val);
listNode = listNode.next;
}

}
}

// 0,1,2
//

参考链接:

206. 反转链表