第21题:Merge Two Sorted Lists

来源:互联网 发布:手机剪辑软件 编辑:程序博客网 时间:2024/05/16 18:25

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.


题目要求:合并两个已排序单链表。


编程语言:javascript

解法:算法复杂度为O(n)  思路:建立一个新的单链表,从头遍历两个单链表,将数值小的节点插入新的单链表中。


/** * 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) {        return mergeTwoLists(l1,l2);        function mergeTwoLists(list1,list2)    {        if(list1 === null) return list2;        if(list2 === null) return list1;                if(list1.val <= list2.val)        {            list1.next = mergeTwoLists(list1.next,list2);            return list1;        }else{            list2.next = mergeTwoLists(list1,list2.next);            return list2;        }    }};




0 0
原创粉丝点击