Skip to content

Commit d28633a

Browse files
Implement merge function for two sorted linked lists
1 parent debae3b commit d28633a

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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 Merge2SortedLL {
12+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
13+
ListNode merged = merge(list1, list2);
14+
15+
return merged;
16+
}
17+
18+
static ListNode merge(ListNode list1, ListNode list2){
19+
if(list1 == null){
20+
return list2;
21+
}
22+
if(list2 == null){
23+
return list1;
24+
}
25+
26+
if(list1.val <= list2.val){
27+
list1.next = merge(list1.next, list2);
28+
return list1;
29+
}
30+
else{
31+
list2.next = merge(list1, list2.next);
32+
return list2;
33+
}
34+
35+
}
36+
}

0 commit comments

Comments
 (0)