算法: 合并兩個(gè)有序鏈表
1. 題目: 將兩個(gè)升序鏈表合并為一個(gè)新的 升序 鏈表并返回。新鏈表是通過(guò)拼接給定的兩個(gè)鏈表的所有節(jié)點(diǎn)組成的。
e.g
輸入:l1 = [1,2,5], l2 = [1,3,4]
輸出:[1,1,2,3,4,5]
2. 思路 (迭代)
我們可以用迭代的方法來(lái)實(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;
};
浙公網(wǎng)安備 33010602011771號(hào)