算法: 合并兩個(gè)有序鏈表

1. 題目: 將兩個(gè)升序鏈表合并為一個(gè)新的 升序 鏈表并返回。新鏈表是通過拼接給定的兩個(gè)鏈表的所有節(jié)點(diǎn)組成的。

e.g
輸入:l1 = [1,2,5], l2 = [1,3,4]
輸出:[1,1,2,3,4,5]

2. 思路 (迭代)

我們可以用迭代的方法來實(shí)現(xiàn)上述算法。當(dāng) l1 和 l2 都不是空鏈表時(shí),判斷 l1 和 l2 哪一個(gè)鏈表的頭節(jié)點(diǎn)的值更小,將較小值的節(jié)點(diǎn)添加到結(jié)果里,當(dāng)一個(gè)節(jié)點(diǎn)被添加到結(jié)果里之后,將對(duì)應(yīng)鏈表中的節(jié)點(diǎn)向后移一位。

3. 代碼

3.1. C#

/**
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public ListNode MergeTwoLists(ListNode l1, ListNode l2) {
 ListNode preHead = new ListNode(-1);
 ListNode pre = preHead;
 while (l1 != null && l2 != null){
 if(l1.val > l2.val){
 pre.next = l2;
 l2 = l2.next;
        }else{
 pre.next = l1;
 l1 = l1.next;
        }
 pre = pre.next;
    }
 pre.next = l1==null? l2:l1;
 return preHead.next;
}

3.2. Javascript

/**
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
var mergeTwoLists = function(l1, l2) {
 if(l1 === null) return l2;
 if(l2 === null) return l1;

 let preHead = new ListNode();
 let last = preHead;
 let cur ;
 while(l1 !=null && l2!= null){
 if(l1.val > l2.val){
 cur = l2;
 l2 = l2.next;
        }else{
 cur = l1;
 l1 = l1.next;
        }
        last.next = cur;
 last = cur;

    }
    last.next = l1 === null? l2:l1;

 return preHead.next;
};
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容