Skip to content

Commit d11e0ca

Browse files
committed
feat: 21. Merge Two Sorted Lists solution
(cherry picked from commit 89322c3554301c0859b5e61e08d20f6ab995533e)
1 parent 86d5e72 commit d11e0ca

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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(-1);
14+
ListNode current = head;
15+
16+
while (list1 != null && list2 != null) {
17+
if (list1.val <= list2.val) {
18+
current.next = list1;
19+
list1 = list1.next;
20+
} else {
21+
current.next = list2;
22+
list2 = list2.next;
23+
}
24+
current = current.next;
25+
}
26+
27+
current.next = (list1 != null) ? list1 : list2;
28+
29+
return head.next;
30+
}
31+
}

0 commit comments

Comments
 (0)