zoukankan      html  css  js  c++  java
  • 剑指offer(十六) 合并两个排序的链表

    合并两个排序的链表
    题目描述
    输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

    用JavaScript非递归和递归方式都AC了。

    非递归:

    function ListNode(x){
        this.val = x;
        this.next = null;
    }
    
    function Merge(pHead1, pHead2)
    {
        if(!pHead1) {
            return !pHead2 ? null:pHead2;
        }else if(!pHead2) {
            return pHead1;
        }
    
        var ans = new ListNode(-1);
        var l1 = pHead1;
        var l2 = pHead2;
        var cur = ans;
        while (l1 && l2) {
            if (l1.val <= l2.val) {
                cur.next = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        if(!l1) {
            cur.next = l2;
        }
        if(!l2) {
            cur.next = l1;
        }
        return ans.next;
    }
    

    最好的写法是结尾在释放掉内存:

    cur = ans.next;
    ans.next = null;
    ans = cur;
    cur = l1 = l2 = null;
    return ans;
    

    如果 ans.next 指向一个对象
    执行 cur = ans.next;
    这时 cur 和 ans.next 将指向同一个对象
    执行 ans.next = null;
    将 ans.next 指向null,但对象不会被垃圾回收,因为还有一个cur变量指向该对象
    执行 ans = cur;
    将 ans 指向对象。再将cur和l1,l2赋值为null。利用的JS的回收机制和对象引用。

    递归:

    function ListNode(x){
        this.val = x;
        this.next = null;
    }
    
    function Merge(pHead1, pHead2)
    {
        if(pHead1 == null) {
            return pHead2;
        }
        if(pHead2 == null) {
            return pHead1;
        }
    
        var ans = null;
        if(pHead1.val <= pHead2.val) {
            ans = pHead1;
            ans.next = Merge(pHead1.next,pHead2);
            return ans;
        }else {
            ans = pHead2;
            ans.next = Merge(pHead2.next,pHead1);
            return ans;
        }
        return ans;
    }
    

    gtihub剑指offerAC代码仓库地址:传送

  • 相关阅读:
    OCP-1Z0-053-V13.02-702题
    OCP-1Z0-053-V13.02-688题
    OCP-1Z0-053-V13.02-691题
    OCP-1Z0-053-V13.02-698题
    OCP-1Z0-053-V13.02-703题
    OCP-1Z0-053-V13.02-701题
    OCP-1Z0-053-V13.02-685题
    memcached 按键查找和批量查找
    catch(CException *e)捕获异常
    char数组最大长度
  • 原文地址:https://www.cnblogs.com/zhangmingzhao/p/8439640.html
Copyright © 2011-2022 走看看