Skip to content

Commit 5c009e6

Browse files
committed
merged two sorted list solved
1 parent fd1f2f9 commit 5c009e6

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
class Solution {
12+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
13+
ListNode answer = new ListNode(0, null);
14+
ListNode merged = answer;
15+
16+
while(list1 != null || list2 != null){
17+
if(list1 == null){
18+
merged.next = list2;
19+
break;
20+
}
21+
if(list2 == null){
22+
merged.next = list1;
23+
break;
24+
}
25+
if(list1.val <= list2.val){
26+
merged.next = list1;
27+
list1 = list1.next;
28+
}
29+
else{
30+
merged.next = list2;
31+
list2 = list2.next;
32+
}
33+
34+
merged = merged.next;
35+
}
36+
37+
return answer.next;
38+
}
39+
}

0 commit comments

Comments
 (0)