algorithm-base/animation-simulation/链表篇/leetcode92反转链表2.md

132 lines
4.5 KiB
Java
Raw Normal View History

2021-03-26 11:58:47 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
2 1 1 [leetcode 206 ](https://github.com/chefyuan/algorithm-base/blob/main/animation-simulation/%E9%93%BE%E8%A1%A8%E7%AF%87/leetcode206%E5%8F%8D%E8%BD%AC%E9%93%BE%E8%A1%A8.md)
#### [92. II](https://leetcode-cn.com/problems/reverse-linked-list-ii/)
836
`head` `left` `right` `left <= right` `left` `right` ****
** 1**
![img](https://assets.leetcode.com/uploads/2021/02/19/rev2ex2.jpg)
> head = [1,2,3,4,5], left = 2, right = 4
> [1,4,3,2,5]
** 2**
> head = [5], left = 1, right = 1
> [5]
1
2021-03-27 08:38:40 +00:00
![](https://img-blog.csdnimg.cn/20210327163804112.gif)
2021-03-26 11:58:47 +00:00
2021-04-28 10:28:00 +00:00
****
Java Code:
2021-03-26 11:58:47 +00:00
```java
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
//虚拟头节点
ListNode temp = new ListNode(-1);
temp.next = head;
ListNode pro = temp;
//来到 left 节点前的一个节点
int i = 0;
for (; i < left-1; ++i) {
pro = pro.next;
}
// 保存 left 节点前的第一个节点
ListNode leftNode = pro;
for (; i < right; ++i) {
pro = pro.next;
}
// 保存 right 节点后的节点
ListNode rightNode = pro.next;
//切断链表
pro.next = null;
ListNode newhead = leftNode.next;
leftNode.next = null;
leftNode.next = rever(newhead);
//重新接头
newhead.next = rightNode;
return temp.next;
}
//和反转链表1代码一致
public ListNode rever (ListNode head) {
ListNode low = null;
ListNode pro = head;
while (pro != null) {
ListNode temp = pro;
pro = pro.next;
temp.next = low;
low = temp;
}
return low;
}
}
```
2021-04-28 10:28:00 +00:00
C++ Code:
```cpp
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode * temp = new ListNode(-1);
temp->next = head;
ListNode * pro = temp;
//来到 left 节点前的一个节点
int i = 0;
for (; i < left-1; ++i) {
pro = pro->next;
}
// 保存 left 节点前的第一个节点
ListNode * leftNode = pro;
for (; i < right; ++i) {
pro = pro->next;
}
// 保存 right 节点后的节点
ListNode * rightNode = pro->next;
//切断链表
pro->next = nullptr;
ListNode * newhead = leftNode->next;
leftNode->next = nullptr;
leftNode->next = rever(newhead);
//重新接头
newhead->next = rightNode;
return temp->next;
}
ListNode * rever (ListNode * head) {
ListNode * low = nullptr;
ListNode * pro = head;
while (pro != nullptr) {
ListNode * temp = pro;
pro = pro->next;
temp->next = low;
low = temp;
}
return low;
}
};
```