merge-two-sorted-lists.dart (1536B)
1 //This was kind of annoying with the null safety of dart 2 //causing there to be ? everywhere. Also, dart is not made for pointers 3 //or singly linked lists. 4 //Time: 280ms Beats: 73.33% 5 //Memory 144.6MB Beats: 22.22% 6 7 class ListNode{ 8 int val = 0; 9 ListNode? next; 10 } 11 12 void main(){ 13 Solution sol = new Solution(); 14 ListNode head1 = new ListNode(); 15 ListNode ln1 = new ListNode(); 16 head1.val = 4; 17 ln1.val = 5; 18 head1.next = ln1; 19 ListNode ln2 = new ListNode(); 20 ln2.val = 10; 21 ln1.next = ln2; 22 ListNode? ln = sol.mergeTwoLists(head1, ln1); 23 while(ln?.val != null){ 24 print(ln?.val); 25 ln = ln?.next; 26 } 27 } 28 29 class Solution { 30 ListNode? mergeTwoLists(ListNode? list1, ListNode? list2) { 31 if(list1?.val == null && list2?.val == null){ 32 return list1 ; 33 } 34 List<int?> vals = []; 35 while(list1?.val != null && list2?.val != null){ 36 vals.add(list2?.val); 37 vals.add(list1?.val); 38 list1 = list1?.next; 39 list2 = list2?.next; 40 } 41 42 while(list1?.val != null){ 43 vals.add(list1?.val); 44 list1 = list1?.next; 45 } 46 while(list2?.val != null){ 47 vals.add(list2?.val); 48 list2 = list2?.next; 49 } 50 vals.sort(); 51 52 ListNode ln = new ListNode(); 53 ListNode ln1 = new ListNode(); 54 ListNode start = ln; 55 for(int i = 0 ; i < vals.length - 1; ++i){ 56 ln.val = vals[i] ?? 0; 57 ln.next = ln1; 58 ln = ln1; 59 ln1 = new ListNode(); 60 } 61 ln.val = vals[vals.length - 1] ?? 0; 62 return start; 63 } 64 }