LeetCode 92_反转链表 II
LeetCode 92:反转链表 II
题目
给你单链表的头指针 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]
思路
遍历至起始节点的前一个节点pre,cur为当前操作节点,后使用for循环,类似头插法,将节点按顺序调整。例如将1->2->3->4->5,调整为1->3->2->4->5,之后当前节点仍然为2,pre仍指向1,cur仍然为2
代码
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode newHead=new ListNode(-1);
newHead.next=head;
ListNode pre=newHead;
for(int i=1;i<left;i++)
{
pre=pre.next;
}
ListNode cur=pre.next;//重要,写在循环外,cur记录的一直是2的位置
for(int i=left;i<right;i++)
{
ListNode nex=cur.next;
cur.next=nex.next;
nex.next=pre.next;
pre.next=nex;
}
return newHead.next;
}
}
反思
①ListNode记录的是链表节点的存储位置,因此cur和pre永远保存2和1的位置