@@ -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) 的元素,注意是左闭右开 */
7777ListNode 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
95109ListNode 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
@@ -135,4 +179,4 @@ ListNode reverseKGroup(ListNode head, int k) {
135179
136180[下一篇:如何判定括号合法性](../高频面试系列/合法括号判定.md)
137181
138- [ 目录] ( ../README.md#目录 )
182+ [目录](../README.md#目录)
0 commit comments