FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm/Week_01/id_21/LeetCode_025_021.cpp 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_21
/
LeetCode_025_021.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
55 lines (48 loc) · 1.15 KB
Breadcrumbs
algorithm
/
Week_01
/
id_21
/
LeetCode_025_021.cpp
Copy path
File metadata and controls
55 lines (48 loc) · 1.15 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
/*
*
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class
Solution
{
public:
ListNode*
reverseKGroup
(ListNode* head,
int
k) {
if
(head ==
nullptr
|| k ==
1
)
return
head;
ListNode* dummy =
new
ListNode
(
0
);
dummy->
next
= head;
ListNode* begin = dummy, *end, * next;
while
(begin !=
nullptr
) {
int
i;
end = begin->
next
;
for
(i =
1
; i < k; i++) {
if
(end ==
nullptr
|| end->
next
==
nullptr
)
break
;
end = end->
next
;
}
if
(i < k)
break
;
next = begin->
next
;
reverse
(begin, end);
begin = next;
}
return
dummy->
next
;
}
/*
* 此函数为左开右闭区间
* 直接修改 begin->next 的指向来完成翻转
*/
void
reverse
(ListNode* begin, ListNode* end) {
end = end->
next
;
ListNode* p1 = begin->
next
, * next;
ListNode* dummy =
new
ListNode
(
0
);
dummy->
next
= end;
while
(p1 != end) {
next = p1->
next
;
p1->
next
= dummy->
next
;
dummy->
next
= p1;
p1 = next;
}
begin->
next
= dummy->
next
;
delete
dummy;
}
};
Back
|
FazBrowse Home
|
New Git URL