• [LeetCode] Reverse Linked List II


    Reverse a linked list from position m to n. Do it in-place and in one-pass.

    For example:
    Given 1->2->3->4->5->NULLm = 2 and n = 4,

    return 1->4->3->2->5->NULL.

    Note:
    Given mn satisfy the following condition:
    1 ≤ m ≤ n ≤ length of list.

    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    /**
     * @param {ListNode} head
     * @param {number} m
     * @param {number} n
     * @return {ListNode}
     */
    var reverseBetween = function(head, m, n) {
        var prev = null;
        var now = head;
        var next = head.next;
        var iprev = null;
        var inext = null;
        var ihead = null;
        var itail = null;
        var s = 1;
        
        var newhead = false;
        
        while (now) {
            if (s >= m && s <= n) {
                if (s == m) {
                    itail = now;
                    iprev = prev;
                }
                if (s == n) {
                    ihead = now;
                    inext = next;
                }
                now.next = prev;
                prev = now;
                now = next;
                if (now) {
                    next = now.next;
                }
                
                if (s == n) {
                    if (!iprev) {
                        head = ihead;
                    } else {
                        iprev.next = ihead;
                    }
                    itail.next = inext;
                    break;
                }
            } else {
                prev = now;
                now = next;
                if (now) {
                    next = now.next;
                }
            }
            s++;
        }
        return head;
    };

    代码比较丑,用了大量的零时变量来存东西,思路跟翻转整个链表那题如出一辙。简述一下思路就是:用三指针prev, now, next 遍历链表,当到达指定范围后开始翻转操作,并顺便记录翻转那部分的头和尾(ihead, itail)还有相应接头部分的指针(iprev, inext)以便最后翻转完了以后把两部分接起来。特别注意的是链表的头可能会被改变。

  • 相关阅读:
    python学习第四天 --字符编码 与格式化及其字符串切片
    Lambda表达式 之 C#
    python学习第三天 --布尔类型
    深入理解正则表达式
    《你不知道的JavaScript》第一部分:作用域和闭包
    jquery的extend和fn.extend
    HttpModule与HttpHandler详解
    jQuery分析(2)
    jQuery分析(1)
    jQuery源码中的“new jQuery.fn.init()”什么意思?
  • 原文地址:https://www.cnblogs.com/agentgamer/p/4908580.html
Copyright © 2020-2023  润新知