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]
提示:
链表中节点数目为 n
1 <= n <= 500
-500 <= Node.val <= 500
1 <= left <= right <= n
进阶: 你可以使用一趟扫描完成反转吗?
Related Topics 链表
👍 923 👎 0
2. 题解
2.1 解法1: 两次遍历
截取需要反转的链表, 反转后再连接
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
if (head == null) {
return null;
}
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
// 第 1 步:pre 指向left的前一个结点, 需要走 left-1 步
ListNode pre = dummyNode;
for (int i = 1; i <= left - 1; i++) {
pre = pre.next;
}
// 第 2 步:从 pre 再走 right - left + 1 步,来到 rightNode 节点
ListNode rightNode = pre;
for (int i = 1; i <= right - left + 1; i++) {
rightNode = rightNode.next;
}
// 第 3 步:切断出一个子链表(截取链表)
ListNode leftNode = pre.next;
ListNode next = rightNode.next;
// 注意:切断链接
pre.next = null;
rightNode.next = null;
// 第 4 步:同第 206 题,反转链表的子区间
reverse(leftNode);
// 第 5 步:接回到原来的链表中
pre.next = rightNode;
leftNode.next = next;
return head;
}
public ListNode reverse(ListNode head) {
if (head == null) {
return null;
}
ListNode pre = null;
ListNode curr = head;
while (curr != null) {
ListNode temp = curr.next;
curr.next = pre;
pre = curr;
curr = temp;
}
return pre;
}
}
2.2 解法2: 一次遍历+头插法
中间保存两个变量, pre 指向待翻转的前驱结点, curr指向待反转区域的第一个节点
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
ListNode curr = dummy.next;
for (int i = 0; i < left - 1; i++) {
pre = pre.next;
curr = curr.next;
}
// 开始反转, 执行 right-left 次, 注意curr 作为最终反转链表的尾结点是不变的, 不需要向前推进
for (int i = 0; i < right - left; i++) {
// 先保存 curr 的后继, 作为头插入
ListNode next = curr.next;
curr.next = next.next;
// 重点! 每次指向当前的已反转链表的头结点, 而不是 cur
next.next = pre.next;
pre.next = next;
}
return dummy.next;
}
}
参考:
官方题解
Java-双指针-头插法