FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm/Week_01/id_108/LeetCode_25_108.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_108
/
LeetCode_25_108.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
81 lines (77 loc) · 2.35 KB
Breadcrumbs
algorithm
/
Week_01
/
id_108
/
LeetCode_25_108.java
Copy path
File metadata and controls
81 lines (77 loc) · 2.35 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
76
77
78
79
80
81
/**
* @author zhangruihao.zhang
* @version v1.0.0
* @since 2019/04/20
*/
public
class
LeetCode_25_108
{
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class
Solution
{
public
ListNode
reverseKGroup
(
ListNode
head
,
int
k
) {
if
(
k
==
1
){
return
head
;
}
if
(
head
==
null
){
return
head
;
}
ListNode
tail
=
needReverse
(
head
,
k
);
if
(
tail
==
null
){
return
head
;
}
//下一组要翻转的起点
ListNode
nextFirst
=
tail
.
next
;
tail
.
next
=
null
;
ListNode
[]
pair
=
reverse
(
head
);
head
=
pair
[
0
];
ListNode
lastTail
=
pair
[
1
];
//翻转起点
ListNode
reverseStart
=
nextFirst
;
while
(
true
){
tail
=
needReverse
(
nextFirst
,
k
);
if
(
tail
==
null
){
lastTail
.
next
=
nextFirst
;
break
;
}
//翻转起点
reverseStart
=
nextFirst
;
//跳到未来的下一组
nextFirst
=
tail
.
next
;
tail
.
next
=
null
;
pair
=
reverse
(
reverseStart
);
lastTail
.
next
=
pair
[
0
];
lastTail
=
pair
[
1
];
}
return
head
;
}
//判断链表是否可以翻转,如果可以翻转,则返回翻转链表的最后一个节点
private
ListNode
needReverse
(
ListNode
head
,
int
k
){
int
i
=
1
;
ListNode
cur
=
head
;
while
(
i
<
k
&&
cur
!=
null
&&
cur
.
next
!=
null
){
cur
=
cur
.
next
;
i
++;
}
return
i
==
k
?
cur
:
null
;
}
//返回翻转后的链表的首尾对
private
ListNode
[]
reverse
(
ListNode
head
){
ListNode
pre
=
head
;
ListNode
cur
=
head
.
next
;
ListNode
tmp
=
cur
==
null
?
null
:
cur
.
next
;
head
.
next
=
null
;
while
(
cur
!=
null
){
cur
.
next
=
pre
;
pre
=
cur
;
cur
=
tmp
;
tmp
=
tmp
==
null
?
null
:
tmp
.
next
;
}
return
new
ListNode
[]{
pre
,
head
};
}
}
}
Back
|
FazBrowse Home
|
New Git URL