题目: 给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。 题目链接
我的JavaScript解法
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} left
* @param {number} right
* @return {ListNode}
*/
var reverseBetween = function(head, left, right) {
if (left === right) return head;
let count = 1;
let newHead = new ListNode(-1, head), leftPre = newHead;
while(count < left) {
leftPre = leftPre.next;
count++;
}
if (!leftPre.next) return head;
let current = leftPre.next, next = current.next, pe = current;
while(count < right) {
const nextNext = next.next;
next.next = current;
pe.next = nextNext;
current = next;
next= nextNext;
count++;
}
leftPre.next = current;
return newHead.next;
};
解析: 链表问题,可以用双指针循环,或者递归
- 时间复杂度:
- 空间复杂度: