Skip to content

Commit c13bf2c

Browse files
tianzhongweilabuladong
authored andcommitted
Update k个一组反转链表.md
添加对应思路的C++代码
1 parent b1ad080 commit c13bf2c

File tree

1 file changed

+48
-4
lines changed

1 file changed

+48
-4
lines changed

高频面试系列/k个一组反转链表.md

Lines changed: 48 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ ListNode reverse(ListNode a) {
7171
「反转以 `a` 为头结点的链表」其实就是「反转 `a` 到 null 之间的结点」,那么如果让你「反转 `a``b` 之间的结点」,你会不会?
7272

7373
只要更改函数签名,并把上面的代码中 `null` 改成 `b` 即可:
74-
74+
[labuladong](https://github.com/labuladong) 提供Java解法代码:
7575
```java
7676
/** 反转区间 [a, b) 的元素,注意是左闭右开 */
7777
ListNode reverse(ListNode a, ListNode b) {
@@ -88,9 +88,23 @@ ListNode reverse(ListNode a, ListNode b) {
8888
return pre;
8989
}
9090
```
91+
[renxiaoyao](https://github.com/tianzhongwei) 提供C++解法代码:
92+
```C++
93+
ListNode* reverse(ListNode* begin,ListNode* end) {
94+
ListNode* newHead = nullptr;
95+
ListNode* cur = begin;
96+
while(cur != end) {
97+
ListNode* next = cur->next;
98+
cur->next = newHead;
99+
newHead = cur;
100+
cur = next;
101+
}
102+
return newHead;
103+
}
104+
```
91105
92106
现在我们迭代实现了反转部分链表的功能,接下来就按照之前的逻辑编写 `reverseKGroup` 函数即可:
93-
107+
[labuladong](https://github.com/labuladong) 提供Java解法代码:
94108
```java
95109
ListNode reverseKGroup(ListNode head, int k) {
96110
if (head == null) return null;
@@ -109,7 +123,37 @@ ListNode reverseKGroup(ListNode head, int k) {
109123
return newHead;
110124
}
111125
```
112-
126+
[renxiaoyao](https://github.com/tianzhongwei) 提供C++解法代码:
127+
```C++
128+
class Solution {
129+
public:
130+
ListNode* reverseKGroup(ListNode* head, int k) {
131+
if(!head) return head;
132+
ListNode* begin = head;
133+
ListNode* end = head;
134+
for(int i = 0 ; i < k ; ++i) {
135+
if(!end)
136+
return head;
137+
end = end->next;
138+
}
139+
ListNode* newHead = reverse(begin,end);
140+
begin->next = reverseKGroup(end,k);
141+
return newHead;
142+
}
143+
private:
144+
ListNode* reverse(ListNode* begin,ListNode* end) {
145+
ListNode* newHead = nullptr;
146+
ListNode* cur = begin;
147+
while(cur != end) {
148+
ListNode* next = cur->next;
149+
cur->next = newHead;
150+
newHead = cur;
151+
cur = next;
152+
}
153+
return newHead;
154+
}
155+
};
156+
```
113157
解释一下 `for` 循环之后的几句代码,注意 `reverse` 函数是反转区间 `[a, b)`,所以情形是这样的:
114158
115159
![](../pictures/kgroup/6.jpg)
@@ -135,4 +179,4 @@ ListNode reverseKGroup(ListNode head, int k) {
135179
136180
[下一篇:如何判定括号合法性](../高频面试系列/合法括号判定.md)
137181
138-
[目录](../README.md#目录)
182+
[目录](../README.md#目录)

0 commit comments

Comments
 (0)