合并两个有序链表(创建新链表往里面添加节点)

将两个有序的链表合并为一个新链表,要求新的链表是通过拼接两个链表的节点来生成的。

/*
 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */

/**
  * 
  * @param l1 ListNode类 
  * @param l2 ListNode类 
  * @return ListNode类
  */
function mergeTwoLists( l1 ,  l2 ) {
    // write code here
    if(l1 == null) { return l2 }
    if(l2 == null) { return l1 }
    var head={}
    var current = head
    while(l1&&l2){
        if(l1.val<l2.val){
            current.next = l1
            current = current.next
            l1 = l1.next
        }else{
            current.next = l2
            current = current.next
            l2 = l2.next
        }
    }
    while(l1){
        current.next =l1
        current = current.next
        l1=l1.next
    }
    while(l2){
        current.next =l2
        current = current.next
        l2=l2.next
    }
    return head.next
}
module.exports = {
    mergeTwoLists : mergeTwoLists
};
链表算法 文章被收录于专栏

链表相关算法

全部评论

相关推荐

LemontreeN:有的兄弟有的我今天一天面了五场,4个二面一个hr面
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
后来123321:别着急,我学院本大二,投了1100份,两个面试,其中一个还是我去线下招聘会投的简历,有时候这东西也得看运气
无实习如何秋招上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务