forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge2sortedlists.java
More file actions
executable file
·41 lines (41 loc) · 975 Bytes
/
merge2sortedlists.java
File metadata and controls
executable file
·41 lines (41 loc) · 975 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
/**
* 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) {
// Start typing your Java solution below
// DO NOT write main() function
ListNode head = new ListNode(0);
ListNode p = head;
ListNode p1 = l1;
ListNode p2 = l2;
while(true){
if(p1==null){
p.next = p2;
break;
}
if(p2==null){
p.next = p1;
break;
}
if(p1.val<p2.val){
p.next = p1;
p = p.next;
p1 = p1.next;
}else{
p.next = p2;
p = p.next;
p2 = p2.next;
}
}
return head.next;
}
}