Skip to content

Commit ed13755

Browse files
committed
commit
1 parent 4f08f04 commit ed13755

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

21. Merge Two Sorted Lists.java

+36
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 Solution {
12+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
13+
ListNode head = new ListNode(); // Empty node
14+
ListNode curr = head;
15+
16+
while (list1 != null && list2 != null) {
17+
if (list1.val <= list2.val) {
18+
curr.next = list1;
19+
20+
list1 = list1.next;
21+
}
22+
else {
23+
curr.next = list2;
24+
25+
list2 = list2.next;
26+
}
27+
28+
curr = curr.next;
29+
}
30+
31+
// Append the remainning nodes
32+
curr.next = (list1 == null) ? list2 : list1;
33+
34+
return head.next;
35+
}
36+
}

0 commit comments

Comments
 (0)