21. Merge Two Sorted Lists

2016-09-21  本文已影响14人  exialym

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.
使用两个指针,比较第一个链表和第二个链表的元素,如果第二个链表的元素大于第一个的,就把第一个指针后移。否则就将第二个指针所指的元素插在第一个指针的前面。这样做不需要一个新的链表来储存,也比较快。

/**
 * 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) {
    var pointer1 = l1;
    var pointer2 = l2;
    while (pointer1!==null&&pointer2!==null) {
        if (pointer1.val<=pointer2.val) {
            if (pointer1.next===null) {
                pointer1.next = pointer2;
                return l1;
            }
            pointer1 = pointer1.next;
        } else {
            var temp = new ListNode(pointer1.val);
            temp.next = pointer1.next;
            pointer1.val = pointer2.val;
            pointer1.next = temp;
            pointer2 = pointer2.next;
        }
        if (pointer2===null) {
            return l1;
        }
        
    }
    return l1 ? l1 : l2;
};
上一篇下一篇

猜你喜欢

热点阅读