92.反转链表-ii
小于 1 分钟
92.反转链表-ii
/*
* @lc app=leetcode.cn id=92 lang=typescript
*
* [92] 反转链表 II
*/
// @lc code=start
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
class ListNode {
val: number;
next: ListNode | null;
constructor(val?: number, next?: ListNode | null) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
}
function reverseBetween(
head: ListNode | null,
left: number,
right: number
): ListNode | null {
const newNode = new ListNode(0, head);
let pre = newNode;
// 找到right的前一位pre
for (let i = 0; i < left - 1; i++) {
pre = pre.next as ListNode; // 必存在
}
let cur = pre.next as ListNode;
// 截止条件left>=right
while (left < right) {
// 将cur+1提到头部
const next = cur.next as ListNode;
cur.next = next.next;
next.next = pre.next;
pre.next = next;
left++;
}
return newNode.next;
}
let tag1 = new ListNode(1);
let tag2 = new ListNode(2);
let tag3 = new ListNode(3);
let tag4 = new ListNode(4);
let tag5 = new ListNode(4);
tag1.next = tag2;
tag2.next = tag3;
tag3.next = tag4;
tag4.next = tag5;
console.log(reverseBetween(tag1, 2, 4));
// @lc code=end
Loading...
