Jack N @ GitHub

Full stack engineer, focus on: Angular/React, node.js/.Net

0%

算法: 合并两个有序链表

1. 题目: 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

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

2. 思路 (迭代)

我们可以用迭代的方法来实现上述算法。当 l1 和 l2 都不是空链表时,判断 l1 和 l2 哪一个链表的头节点的值更小,将较小值的节点添加到结果里,当一个节点被添加到结果里之后,将对应链表中的节点向后移一位。

3. 代码

3.1. C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* 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;
};