From 3ff6b7a3786bb6feed93383e838835cd772542ec Mon Sep 17 00:00:00 2001 From: Laitooo Date: Sun, 8 Jan 2023 16:58:49 +0200 Subject: [PATCH] Create: 0021-Merge-Two-Sorted-Lists.dart --- dart/0021-merge-two-sorted-lists.dart | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 dart/0021-merge-two-sorted-lists.dart diff --git a/dart/0021-merge-two-sorted-lists.dart b/dart/0021-merge-two-sorted-lists.dart new file mode 100644 index 000000000..a608a0069 --- /dev/null +++ b/dart/0021-merge-two-sorted-lists.dart @@ -0,0 +1,26 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode? next; + * ListNode([this.val = 0, this.next]); + * } + */ +class Solution { + ListNode? mergeTwoLists(ListNode? list1, ListNode? list2) { + ListNode? head = ListNode(); + ListNode? cur = head; + while (list1 != null && list2 != null) { + if (list1!.val < list2!.val) { + cur!.next = list1; + list1 = list1!.next; + } else { + cur!.next = list2; + list2 = list2!.next; + } + cur = cur!.next; + } + cur!.next = (list1 == null) ? list2 : list1; + return head.next; + } +} \ No newline at end of file