21. 合并两个有序链表

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null){
return l2;
}

if(l2 == null){
return l1;
}

// 以l1为主
ListNode cur1 = l1;
ListNode cur2 = l2;
ListNode root = new ListNode(-1);
ListNode cur = root;

while(cur1 != null && cur2 != null){
if(cur1.val <= cur2.val){
cur.next = cur1;
cur = cur.next;
cur1 = cur1.next;
}else{
cur.next = cur2;
cur = cur.next;
cur2 = cur2.next;
}
}

// 遍历链表还没走完的部分
if(cur1 != null){
cur.next = cur1;
}

if(cur2 != null){
cur.next = cur2;
}

return root.next;
}
}