Skip to content

Commit 9c6f4b2

Browse files
authored
Merge pull request neetcode-gh#1962 from laitooo/0021-merge-two-sorted-lists.dart
Create: 0021-Merge-Two-Sorted-Lists.dart
2 parents 38d9425 + 3ff6b7a commit 9c6f4b2

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

dart/0021-merge-two-sorted-lists.dart

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* class ListNode {
4+
* int val;
5+
* ListNode? next;
6+
* ListNode([this.val = 0, this.next]);
7+
* }
8+
*/
9+
class Solution {
10+
ListNode? mergeTwoLists(ListNode? list1, ListNode? list2) {
11+
ListNode? head = ListNode();
12+
ListNode? cur = head;
13+
while (list1 != null && list2 != null) {
14+
if (list1!.val < list2!.val) {
15+
cur!.next = list1;
16+
list1 = list1!.next;
17+
} else {
18+
cur!.next = list2;
19+
list2 = list2!.next;
20+
}
21+
cur = cur!.next;
22+
}
23+
cur!.next = (list1 == null) ? list2 : list1;
24+
return head.next;
25+
}
26+
}

0 commit comments

Comments
 (0)