92. 反转链表 II
题目链接
https://leetcode.cn/problems/reverse-linked-list-ii/
相关算法
链表
题目描述
给你单链表的头指针 head
和两个整数 left
和 right
,其中 left <= right
。请你反转从位置 left
到位置 right
的链表节点,返回 反转后的链表 。
数据范围:
- 链表中节点数目为
n
1 <= n <= 500
-500 <= Node.val <= 500
1 <= left <= right <= n
解题思路
链表题有个特点,只要舍得定义临时变量,就能较轻松的做出来。今天这题是调整了反转链表,改为部分反转,对于这个需求,我们可以通过头插和尾插法相结合来实现。已知在 [left, right]
区间处需要进行反转操作,我们可以在小于 left
的地方进行尾插操作,在反转区间内进行头插操作,最后在大于 right
的地方进行尾插即可。题目中需要注意进行完头插操作后,此时的临时头结点还是开始头插操作时的位置,我们需要把它移动到链表的最后再开始进行尾插操作。
完整代码
/**
* 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 reverseBetween(ListNode head, int left, int right) {
ListNode newHead = new ListNode(0, null);
// 记录新链表节点位置
ListNode temp = newHead;
// 记录原链表节点位置
ListNode pNode = head;
int count = 1;
while (count < left) {
ListNode next = pNode.next;
pNode.next = temp.next;
temp.next = pNode;
pNode = next;
temp = temp.next;
count++;
}
while (count <= right && pNode != null) {
ListNode next = pNode.next;
pNode.next = temp.next;
temp.next = pNode;
pNode = next;
count++;
}
while (temp.next != null) {
temp = temp.next;
}
while (pNode != null) {
ListNode next = pNode.next;
pNode.next = temp.next;
temp.next = pNode;
pNode = next;
temp = temp.next;
}
return newHead.next;
}
}
- 时间复杂度:
O(n)
- 空间复杂度:
O(1)