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
51
52
53
54
55
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
//new a head to return;
ListNode head = null;
//check two heads are available to merge
if(list1 == null){
return list2;
}
if(list2 == null){
return list1;
}
if(list1 == null && list2 == null){
return head;
}

//build three pointers, cur for the last element in the sorted linkedlist;
//cur1 for the first element in the list1;
//cur2 for the first element in the list2;
//we can decide the head now;
ListNode cur1;
ListNode cur2;
if(list1.val > list2.val){
head = list2;
cur1 = list1;
cur2 = list2.next;

}
else{
head = list1;
cur1 = list1.next;
cur2 = list2;
}
ListNode cur = head;

//while loop to check which one is biger, until one of pointers of one list is null;
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;
}
}
//check which list pointer is null; direct use 'cur' point to the pointer which still has linkedlist left;
if(cur1 != null){
cur.next = cur1;
}
else{
cur.next = cur2;
}
return head;
}