提交 c13bf2cd 编写于 作者: T tianzhongwei 提交者: labuladong

Update k个一组反转链表.md

添加对应思路的C++代码
上级 b1ad080a
......@@ -71,7 +71,7 @@ ListNode reverse(ListNode a) {
「反转以 `a` 为头结点的链表」其实就是「反转 `a` 到 null 之间的结点」,那么如果让你「反转 `a``b` 之间的结点」,你会不会?
只要更改函数签名,并把上面的代码中 `null` 改成 `b` 即可:
[labuladong](https://github.com/labuladong) 提供Java解法代码:
```java
/** 反转区间 [a, b) 的元素,注意是左闭右开 */
ListNode reverse(ListNode a, ListNode b) {
......@@ -88,9 +88,23 @@ ListNode reverse(ListNode a, ListNode b) {
return pre;
}
```
[renxiaoyao](https://github.com/tianzhongwei) 提供C++解法代码:
```C++
ListNode* reverse(ListNode* begin,ListNode* end) {
ListNode* newHead = nullptr;
ListNode* cur = begin;
while(cur != end) {
ListNode* next = cur->next;
cur->next = newHead;
newHead = cur;
cur = next;
}
return newHead;
}
```
现在我们迭代实现了反转部分链表的功能,接下来就按照之前的逻辑编写 `reverseKGroup` 函数即可:
[labuladong](https://github.com/labuladong) 提供Java解法代码:
```java
ListNode reverseKGroup(ListNode head, int k) {
if (head == null) return null;
......@@ -109,7 +123,37 @@ ListNode reverseKGroup(ListNode head, int k) {
return newHead;
}
```
[renxiaoyao](https://github.com/tianzhongwei) 提供C++解法代码:
```C++
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(!head) return head;
ListNode* begin = head;
ListNode* end = head;
for(int i = 0 ; i < k ; ++i) {
if(!end)
return head;
end = end->next;
}
ListNode* newHead = reverse(begin,end);
begin->next = reverseKGroup(end,k);
return newHead;
}
private:
ListNode* reverse(ListNode* begin,ListNode* end) {
ListNode* newHead = nullptr;
ListNode* cur = begin;
while(cur != end) {
ListNode* next = cur->next;
cur->next = newHead;
newHead = cur;
cur = next;
}
return newHead;
}
};
```
解释一下 `for` 循环之后的几句代码,注意 `reverse` 函数是反转区间 `[a, b)`,所以情形是这样的:
![](../pictures/kgroup/6.jpg)
......@@ -135,4 +179,4 @@ ListNode reverseKGroup(ListNode head, int k) {
[下一篇:如何判定括号合法性](../高频面试系列/合法括号判定.md)
[目录](../README.md#目录)
\ No newline at end of file
[目录](../README.md#目录)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册