-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
54 lines (45 loc) · 1.18 KB
/
Solution.java
File metadata and controls
54 lines (45 loc) · 1.18 KB
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null)
return l2;
if (l2 == null)
return l1;
ListNode nodeP = l1;
ListNode nodeQ = l2;
ListNode head = null;
ListNode curr = null;
if (nodeP.val < nodeQ.val) {
head = nodeP;
nodeP = nodeP.next;
} else {
head = nodeQ;
nodeQ = nodeQ.next;
}
curr = head;
while (nodeP != null && nodeQ != null) {
if (nodeP.val < nodeQ.val) {
curr.next = nodeP;
nodeP = nodeP.next;
} else {
curr.next = nodeQ;
nodeQ = nodeQ.next;
}
curr = curr.next;
}
if (nodeP == null) {
curr.next = nodeQ;
}
if (nodeQ == null) {
curr.next = nodeP;
}
return head;
}
}