Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

反转链表 II

Sunny-117 opened this issue · comments

commented
/**
 * @param {ListNode} head
 * @param {number} left
 * @param {number} right
 * @return {ListNode}
 */
var reverseBetween = function(head, left, right) {
    const dummyNode = new ListNode(-1);
    dummyNode.next = head;

    let pre = dummyNode;
    for(let i = 0; i < left - 1; i++){ //将pre移动到left的前一个节点
        pre = pre.next
    }

    let rightNode = pre;
    for(let i = 0; i < right - left + 1; i++){
        //rightNode移动到right所指向的节点
        rightNode = rightNode.next
    }

    //截取链表
    let leftNode = pre.next;
    let curr = rightNode.next; //right节点的下一个节点
    pre.next = null;
    rightNode.next = null;

    //反转链表
    reverseLinkList(leftNode);
    //接回原链表
    pre.next = rightNode;
    leftNode.next = curr; //反转之后leftNode后面接curr
    return dummyNode.next
};
const reverseLinkList = (head) => {
    let prev = null;
    let curr = head;

    while(curr){
        let next = curr.next;
        curr.next = prev;
        prev = curr
        curr = next
    }
}
commented

题目链接:https://leetcode.cn/problems/reverse-linked-list-ii
时间复杂度:O(n)
空间复杂度:O(1)

/**
 * 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) {
    let last=head;
    for(let i=1;i+1<left;i++) last=last.next;
    let node1=last.next;
    if(left===1) node1=last;
    let pre=node1;
    let node=null;
    for(let i=left;i<=right;i++)
    {
        let next=node1.next;
        node1.next=node;
        node=node1;
        if(i!==right) node1=next;
        if(i===right) pre.next=next;
    }
    if(left!==1) last.next=node1;
    else head=node1;

    return head;
};
/**
 * 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) {
    let dummy = new ListNode(null, head);
    let Lnode = dummy;

    // 先找到要翻转的前面那个节点
    for(let i = 0; i < left - 1; i++) {
        Lnode = Lnode.next;
    }

    // 先翻转区间
    let pre = Lnode.next, cur = pre.next;
    for(let i = 0; i < right - left; i++) {
        let ne = cur.next;
        cur.next = pre;
        pre = cur;
        cur = ne;
    }

    // 重新指向
    Lnode.next.next = cur;
    Lnode.next = pre;

    return dummy.next;

};