FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm/Week_01/id_1/LeetCode_25_1.java at master · feixiangcode/algorithm · GitHub
feixiangcode
/
algorithm
Public
forked from
algorithm001/algorithm
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithm
/
Week_01
/
id_1
/
LeetCode_25_1.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
75 lines (64 loc) · 2.25 KB
Breadcrumbs
algorithm
/
Week_01
/
id_1
/
LeetCode_25_1.java
Copy path
File metadata and controls
75 lines (64 loc) · 2.25 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
class
Solution
{
ListNode
preGroupTail
=
null
;
ListNode
result
=
null
;
public
ListNode
reverseKGroup
(
ListNode
head
,
int
k
) {
if
(
head
==
null
||
head
.
next
==
null
||
k
==
1
) {
return
head
;
}
int
index
=
1
;
ListNode
groupHead
=
head
;
ListNode
groupTail
=
head
;
while
(
true
) {
if
(
index
!=
k
) {
// 查找 k 个节点中的 head 和 tail 节点
groupTail
=
groupTail
.
next
;
if
(
groupTail
!=
null
) {
index
++;
continue
;
}
else
{
// 链表长度小于 K 的情况
if
(
this
.
preGroupTail
!=
null
) {
this
.
preGroupTail
.
next
=
groupHead
;
break
;
}
else
{
return
head
;
}
}
}
else
{
// 个数达到 k 时执行交换,返回下一组的 head 节点
ListNode
node
=
this
.
swap
(
groupHead
,
groupTail
);
if
(
node
==
null
) {
break
;
}
groupHead
=
node
;
groupTail
=
node
;
index
=
1
;
}
}
return
result
;
}
private
ListNode
swap
(
ListNode
head
,
ListNode
tail
) {
// 反转链表
ListNode
preNode
=
null
;
ListNode
currentNode
=
head
;
while
(
currentNode
!=
tail
) {
ListNode
next
=
currentNode
.
next
;
currentNode
.
next
=
preNode
;
preNode
=
currentNode
;
currentNode
=
next
;
}
// 当前组的 tail 节点执行 swap
ListNode
node
=
currentNode
.
next
;
currentNode
.
next
=
preNode
;
// 反转完成,将上一组的 tail 节点指向当前组的 head 节点
// 第一次反转时上一组 tail 为 null,因此要执行判空操作
if
(
this
.
preGroupTail
!=
null
) {
this
.
preGroupTail
.
next
=
currentNode
;
}
else
{
// 上一组的 tail 为空说明是第一组执行交换
// 结果一定是第一组交换后的 head 节点
result
=
currentNode
;
}
this
.
preGroupTail
=
head
;
return
node
;
}
}
Back
|
FazBrowse Home
|
New Git URL