-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy path44_mergeTwoLists.java
46 lines (45 loc) · 1.04 KB
/
44_mergeTwoLists.java
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
public class Solution {
/**
* @param ListNode l1 is the head of the linked list
* @param ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
// write your code here
ListNode head = null;
ListNode tmp = null;
ListNode node = null;
while(true){
if(l1==null||l2==null)
break;
else if(l1.val<l2.val){
node = new ListNode(l1.val);
l1 = l1.next;
}else{
node = new ListNode(l2.val);
l2 = l2.next;
}
if(head==null){
head = node;
tmp = head;
}
else{
tmp.next = node;
tmp = tmp.next;
}
}
if(l1!=null){
if(tmp==null)
head = l1;
else
tmp.next = l1;
}
else if(l2!=null){
if(tmp==null)
head = l2;
else
tmp.next = l2;
}
return head;
}
}