04、反转链表2
大约 2 分钟数据结构算法算法基地面试刷题
题目描述
今天我们来说一下反转链表 2,其实这个和 1 的思路差不多,今天先说一个比较好理解的方法,完全按照反转链表 1 的方法来解决,大家看这个题目之前要先看一下反转链表。
下面我们先来看一下题目。
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
示例 1:

输入:head = [1,2,3,4,5], left = 2, right = 4 输出:[1,4,3,2,5]
示例 2:
输入:head = [5], left = 1, right = 1 输出:[5]
题目解析
含义就是让我们反转部分链表。也就是上面蓝色的部分,那我们怎么借助 1 的方法来解决呢?
我们主要通过两部分来解决,先截取需要翻转的部分,然后再头尾交换即可。下面我们通过一个动画来看看具体步骤。

是不是很容易理解,下面我们来看代码吧。
代码
Java Code:
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;
//来到 right 节点
for (; i < right; ++i) {
pro = pro.next;
}
//保存 right 节点后的一个节点
ListNode rightNode = pro.next;
//切断链表
pro.next = null;//切断 right 后的部分
ListNode newhead = leftNode.next;//保存 left 节点
leftNode.next = null;//切断 left 前的部分
//反转
leftNode.next = reverse(newhead);
//重新接头
newhead.next = rightNode;
return temp.next;
}
//和反转链表1代码一致
public ListNode reverse (ListNode head) {
ListNode low = null;
ListNode pro = head;
while (pro != null) {
ListNode temp = pro;
pro = pro.next;
temp.next = low;
low = temp;
}
return low;
}
}
C++ Code:
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;
//来到 right 节点
for (; i < right; ++i) {
pro = pro->next;
}
//保存 right 节点后的一个节点
ListNode * rightNode = pro->next;
//切断链表
pro->next = nullptr;//切断 right 后的部分
ListNode * newhead = leftNode->next;//保存 left 节点
leftNode->next = nullptr;//切断 left 前的部分
//反转
leftNode->next = reverse(newhead);
//重新接头
newhead->next = rightNode;
return temp->next;
}
//和反转链表1代码一致
ListNode * reverse (ListNode * head) {
ListNode * low = nullptr;
ListNode * pro = head;
while (pro != nullptr) {
ListNode * temp = pro;
pro = pro->next;
temp->next = low;
low = temp;
}
return low;
}
};





