mirror of
https://github.com/labuladong/fucking-algorithm.git
synced 2025-07-07 13:57:37 +08:00
Update 递归反转链表的一部分.md
Add C++ Version
This commit is contained in:
@ -218,4 +218,49 @@ ListNode reverseBetween(ListNode head, int m, int n) {
|
|||||||
<img src="../pictures/qrcode.jpg" width=200 >
|
<img src="../pictures/qrcode.jpg" width=200 >
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
======其他语言代码======
|
======其他语言代码======
|
||||||
|
|
||||||
|
[shilei](https://github.com/ShileiGuo) 提供C++解法代码:
|
||||||
|
|
||||||
|
思想:
|
||||||
|
|
||||||
|
1.head表示需要反转的头节点,pre表示需要反转头节点的前驱节点
|
||||||
|
|
||||||
|
2.对于从m到n的节点反转,需要反转n-m次,将head的next节点移动到需要反转链表部分的首部,需要反转链表部分剩余节点依旧保持相对顺序即可
|
||||||
|
|
||||||
|
3.示例 当m=2, n=5时
|
||||||
|
|
||||||
|
第一次反转:1(pre) 2(head) 3(next) 4 5 反转为 1 3 2 4 5
|
||||||
|
|
||||||
|
第二次反转:1(pre) 3 2(head) 4(next) 5 反转为 1 4 3 2 5
|
||||||
|
|
||||||
|
第三次发转:1(pre) 4 3 2(head) 5(next) 反转为 1 5 4 3 2
|
||||||
|
|
||||||
|
```CPP
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
ListNode* reverseBetween(ListNode* head, int m, int n) {
|
||||||
|
//初始化哨兵节点
|
||||||
|
ListNode* dummy=new ListNode(-1);
|
||||||
|
//初始化待反转区间的前一个节点
|
||||||
|
ListNode* pre=dummy;
|
||||||
|
//哨兵节点下一个节点指向head头节点
|
||||||
|
dummy->next=head;
|
||||||
|
|
||||||
|
//获取待反转节点的前一个节点
|
||||||
|
for(int i=0;i<m-1;i++)
|
||||||
|
pre=pre->next;
|
||||||
|
//获取待反转节点的第一个节点
|
||||||
|
head=pre->next;
|
||||||
|
//迭代反转n-m次,将head的next节点移动到需要反转链表部分的首部
|
||||||
|
for(int i=m;i<n;i++){
|
||||||
|
ListNode* t=head->next;
|
||||||
|
head->next=t->next;
|
||||||
|
t->next=pre->next;
|
||||||
|
pre->next=t;
|
||||||
|
}
|
||||||
|
//返回哨兵节点
|
||||||
|
return dummy->next;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
Reference in New Issue
Block a user