-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path0025.k-个一组翻转链表.java
103 lines (98 loc) · 2.25 KB
/
0025.k-个一组翻转链表.java
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
* @lc app=leetcode.cn id=25 lang=java
*
* [25] K 个一组翻转链表
*
* https://leetcode.cn/problems/reverse-nodes-in-k-group/description/
*
* algorithms
* Hard (67.69%)
* Likes: 1827
* Dislikes: 0
* Total Accepted: 406.7K
* Total Submissions: 600.8K
* Testcase Example: '[1,2,3,4,5]\n2'
*
* 给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。
*
* k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
*
* 你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
*
*
*
* 示例 1:
*
*
* 输入:head = [1,2,3,4,5], k = 2
* 输出:[2,1,4,3,5]
*
*
* 示例 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) 额外内存空间的算法解决此问题吗?
*
*
*
*
*/
// @lc code=start
/**
* 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 dummy = new ListNode(0, head);
ListNode pre = dummy, tail = dummy;
while (tail != null) {
for (int i = 0; i < k && tail != null; i++)
tail = tail.next;
if (tail == null)
break;
ListNode start = pre.next, post = tail.next;
tail.next = null;
pre.next = reverse(start);
start.next = post;
pre = start;
tail = pre;
}
return dummy.next;
}
private ListNode reverse(ListNode head) {
ListNode current = head;
head = null;
while (current != null) {
ListNode next = current.next;
current.next = head;
head = current;
current = next;
}
return head;
}
}
// @lc code=end