Skip to content

Commit 415dffe

Browse files
authored
【92. 反转链表 II】【C++】
【92. 反转链表 II】【C++】
2 parents 5771430 + 06c5711 commit 415dffe

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

数据结构系列/递归反转链表的一部分.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,54 @@ ListNode reverseBetween(ListNode head, int m, int n) {
220220

221221
======其他语言代码======
222222

223+
### c++
224+
225+
[shilei](https://github.com/ShileiGuo) 提供C++解法代码:
226+
227+
思想:
228+
229+
1.head表示需要反转的头节点,pre表示需要反转头节点的前驱节点
230+
231+
2.对于从m到n的节点反转,需要反转n-m次,将head的next节点移动到需要反转链表部分的首部,需要反转链表部分剩余节点依旧保持相对顺序即可
232+
233+
3.示例 当m=2, n=5时
234+
235+
第一次反转:1(pre) 2(head) 3(next) 4 5 反转为 1 3 2 4 5
236+
237+
第二次反转:1(pre) 3 2(head) 4(next) 5 反转为 1 4 3 2 5
238+
239+
第三次发转:1(pre) 4 3 2(head) 5(next) 反转为 1 5 4 3 2
240+
241+
```CPP
242+
class Solution {
243+
public:
244+
ListNode* reverseBetween(ListNode* head, int m, int n) {
245+
//初始化哨兵节点
246+
ListNode* dummy=new ListNode(-1);
247+
//初始化待反转区间的前一个节点
248+
ListNode* pre=dummy;
249+
//哨兵节点下一个节点指向head头节点
250+
dummy->next=head;
251+
252+
//获取待反转节点的前一个节点
253+
for(int i=0;i<m-1;i++)
254+
pre=pre->next;
255+
//获取待反转节点的第一个节点
256+
head=pre->next;
257+
//迭代反转n-m次,将head的next节点移动到需要反转链表部分的首部
258+
for(int i=m;i<n;i++){
259+
ListNode* t=head->next;
260+
head->next=t->next;
261+
t->next=pre->next;
262+
pre->next=t;
263+
}
264+
//返回哨兵节点
265+
return dummy->next;
266+
}
267+
};
268+
```
269+
270+
### python
223271
[DiamondI](https://github.com/DiamondI) 提供python3版本代码:
224272
225273
思路:递归。时间复杂度为O(n),由于递归调用需要借助栈的空间,因此空间复杂度亦为O(n)。

0 commit comments

Comments
 (0)