-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMerge Two Sorted Lists.java
More file actions
44 lines (32 loc) · 982 Bytes
/
Merge Two Sorted Lists.java
File metadata and controls
44 lines (32 loc) · 982 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
39
40
41
42
43
44
//https://www.interviewbit.com/problems/merge-two-sorted-lists/
/**
* Definition for singly-linked list.
* class ListNode {
* public int val;
* public ListNode next;
* ListNode(int x) { val = x; next = null; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode A, ListNode B) {
if(A.val > B.val)
return mergeTwoLists(B, A);
ListNode head = A, p = A;
A = A.next;
while(A!=null && B!=null){
if(A.val < B.val){
p.next = A;
A = A.next;
} else {
p.next = B;
B = B.next;
}
p = p.next;
}
if(B == null && A != null)
p.next = A;
if(A == null && B != null)
p.next = B;
return head;
}
}