题目来源:反转链表Ⅱ
在bilibili上的视频讲解:https://www.bilibili.com/video/BV1Cu4y1T7v6/
更多算法知识可微信搜索:算法图解笔记
题目描述
给你单链表的头指针 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
解题思路
思路步骤
step1:定义一个虚拟头节点empty和一个cur指针,同时计算需要反转区间节点的个数k(即需要反转的节点)
- empty的next指向head头节点
- cur指向empty,表示不需要反转节点的尾节点
- k = right - left + 1
这里说明一下为什么需要定义虚拟头节点,因为是指定区间,left是变化的,要是left为1,就需要对头节点进行反转
总结一下就是,对链表操作时,如果涉及到对头节点的操作,就要需要定义一个虚拟头节点
step2:将cur指针移动到需要反转区间链表的前一个节点
step3:反转区间链表操作,将cur的下一个节点进行反转操作,与反转链表的思路是一样的(这里就不在叙述了,不理解的直接点击链接查看),但需要注意的是:
- 迭代结束的条件变了,当k为0时结束迭代
- 反转区间链表的头节点的next需要指向后段不需要反转链表的头节点fast
step4:cur的next指向反转操作后返回的链表,即完成了指定区间链表的反转,返回empty.next
思路动画
代码
Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseK(self, head, k):
fast = head
slow = head
pre = None
while k:
fast = fast.next
slow.next = pre
pre = slow
slow = fast
k -= 1
head.next = fast
return pre
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
empty = ListNode()
empty.next = head
cur = empty
k = right - left + 1
while left - 1 and cur:
cur = cur.next
left -= 1
cur.next = self.reverseK(cur.next, k)
return empty.next
C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseK(ListNode* head, int k) {
ListNode* fast = head;
ListNode* slow = head;
ListNode* pre = nullptr;
while (k) {
fast = fast->next;
slow->next = pre;
pre = slow;
slow = fast;
k--;
}
head->next = fast;
return pre;
}
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode* empty = new ListNode(0);
empty->next = head;
ListNode* cur = empty;
int k = right - left + 1;
while (left - 1 && cur) {
cur = cur->next;
left--;
}
cur->next = reverseK(cur->next, k);
return empty->next;
}
};
Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseK(ListNode head, int k) {
ListNode fast = head;
ListNode slow = head;
ListNode pre = null;
while (k > 0) {
fast = fast.next;
slow.next = pre;
pre = slow;
slow = fast;
k--;
}
head.next = fast;
return pre;
}
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode empty = new ListNode(0);
empty.next = head;
ListNode cur = empty;
int k = right - left + 1;
while (left > 1 && cur != null) {
cur = cur.next;
left--;
}
cur.next = reverseK(cur.next, k);
return empty.next;
}
}