zoukankan      html  css  js  c++  java
  • 21. Merge Two Sorted Lists(js)

    21. Merge Two Sorted Lists

    Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

    Example:

    Input: 1->2->4, 1->3->4
    Output: 1->1->2->3->4->4
    题意:按照大小顺序合并两个链表
    代码如下:
    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    /**
     * @param {ListNode} l1
     * @param {ListNode} l2
     * @return {ListNode}
     */
    var mergeTwoLists = function(l1, l2) {
         //判断两链表是否为空
            if(!l1 || !l2) return l1===null?l2:l1;
            if(!l1 && !l2) return null;
            
            //创建新链表存储结果,
            let head;
            //创建指针分别沿着l1,l2遍历
            let node1=l1,node2=l2;
            //比较l1,l2头结点,较小的赋给新链表
            if(l1.val>l2.val){
                head=l2;
                node2=node2.next;
            }else{
                head=l1;
                node1=node1.next;
            }
            //创建指针沿着新链表移动
            let node=head;
            //不断比较两链表对应节点,直到其中一链表到尾
            while(node1 && node2){
                if(node1.val>node2.val){
                    node.next=node2;
                    node=node.next;
                    node2=node2.next;
                }else{
                    node.next=node1;
                    node=node.next;
                    node1=node1.next;
                }
            }
            
            //判断两链表谁先到头
            if(!node1 && !node2){
                return head;
            }
            if(!node2&&node1){
                node.next=node1;
            }
            if(!node1&& node2){
                node.next=node2;
            }
            
            return head;
    };
  • 相关阅读:
    MD5 加密 以及 加盐加密
    github--新手使用错误分析
    iOS开发UI篇—UITabBarController简单介绍
    Xcode 那些简单实用的插件推荐
    app 转caf 音频 代码
    关于block 用法
    iOS 之播放系统声音
    ios如何实现推送通知
    Centos7安装Redis
    SpringCloud-Zuul网关
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10387366.html
Copyright © 2011-2022 走看看