Merge Two Sorted Lists

 1 /**
 2  * Definition for singly-linked list.
 3  * function ListNode(val) {
 4  *     this.val = val;
 5  *     this.next = null;
 6  * }
 7  */
 8 /**
 9  * @param {ListNode} l1
10  * @param {ListNode} l2
11  * @return {ListNode}
12  */
13 var mergeTwoLists = function(l1, l2) {
14     var ret = new ListNode(0),
15         p = ret;
16 
17     while (l1 !== null && l2 !== null) {
18         if (l1.val < l2.val) {
19             p.next = l1;
20             l1 = l1.next;
21         } else {
22             p.next = l2;
23             l2 = l2.next;
24         }
25 
26         p = p.next;
27     }
28 
29     if (l1 !== null) {
30         p.next = l1;
31     }
32 
33     if (l2 !== null) {
34         p.next = l2;
35     }
36 
37     return ret.next;
38 };

 

posted @ 2015-12-24 20:28  叫我霍啊啊啊  阅读(75)  评论(0编辑  收藏  举报