-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path21. Merge Two Sorted Lists.java
43 lines (40 loc) · 1.09 KB
/
21. Merge Two Sorted Lists.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
/**
* 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 list1, ListNode list2) {
ListNode cur1 = list1;
ListNode cur2 = list2;
ListNode head = new ListNode(0, null);
ListNode tmp = head;
while(cur1 != null && cur2 != null) {
if(cur1.val <= cur2.val) {
tmp.next = cur1;
cur1 = cur1.next;
}
else {
tmp.next = cur2;
cur2 = cur2.next;
}
tmp = tmp.next;
}
while(cur1 != null) {
tmp.next = cur1;
cur1 = cur1.next;
tmp = tmp.next;
}
while(cur2 != null) {
tmp.next = cur2;
cur2 = cur2.next;
tmp = tmp.next;
}
return head.next;
}
}