-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeTwoSortedLists_21.java
More file actions
38 lines (33 loc) · 1006 Bytes
/
MergeTwoSortedLists_21.java
File metadata and controls
38 lines (33 loc) · 1006 Bytes
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
/**
* The solution said using dummy head
*
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*
*
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
/// XXXXXXXXXXXXX Empty Set
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode cur1 = l1, cur2 = l2, head = null, cur = null;
if (cur1.val < cur2.val) { head = cur1; cur1 = cur1.next; }
else { head = cur2; cur2 = cur2.next; }
cur = head;
while(cur1 != null && cur2 != null) {
if (cur1.val < cur2.val) { cur.next = cur1; cur1 = cur1.next; }
else { cur.next = cur2; cur2 = cur2.next; }
cur = cur.next;
}
cur.next = (cur1 == null) ? cur2 : cur1;
return head; /// XXXXXX Return Statement
}
}