leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

merge-two-sorted-listsV2.dart (1653B)


      1 //Made list only add if the value in one of the lists is larger than the other
      2 //this made it so that I did not have to run an O(nlog(n)) sort after the list is
      3 //fully setup.
      4 
      5 //Time: 253ms Beats: 95.56%
      6 //Memory 144MB Beats: 40.47%
      7 
      8 class ListNode{
      9     int val = 0;
     10     ListNode? next;
     11 }
     12 
     13 void main(){
     14     Solution sol = new Solution();
     15     ListNode head1 = new ListNode();
     16     ListNode ln1 = new ListNode();
     17     head1.val = 4;
     18     ln1.val = 5;
     19     head1.next = ln1;
     20     ListNode ln2 = new ListNode();
     21     ln2.val = 10;
     22     ln1.next = ln2;
     23     ListNode? ln = sol.mergeTwoLists(head1, ln1);
     24     while(ln?.val != null){
     25         print(ln?.val);
     26         ln = ln?.next;
     27     }
     28 }
     29 class Solution {
     30   ListNode? mergeTwoLists(ListNode? list1, ListNode? list2) {
     31       
     32     if(list1?.val == null && list2?.val == null){
     33       return list1 ;
     34     }
     35 
     36     List<int?> vals = [];
     37 
     38     while(list1?.val != null && list2?.val != null){
     39       int? v1 = list1?.val;
     40       int? v2 = list2?.val;
     41       if((v1 ?? 0) > (v2 ?? 0)){
     42         vals.add(v2);
     43         list2 = list2?.next;
     44       }
     45       else{
     46         vals.add(v1);
     47         list1 = list1?.next;
     48       }
     49 
     50 
     51 
     52 
     53     }
     54     while(list1?.val != null){
     55       vals.add(list1?.val);
     56       list1 = list1?.next;
     57 
     58     }
     59     while(list2?.val != null){
     60       vals.add(list2?.val);
     61       list2 = list2?.next;
     62 
     63     }
     64     
     65     ListNode ln = new ListNode();
     66     ListNode ln1 = new ListNode();
     67     ListNode start = ln;
     68     for(int i = 0 ; i < vals.length - 1; ++i){
     69       ln.val = vals[i] ?? 0;
     70       ln.next = ln1;
     71       ln = ln1;
     72       ln1 = new ListNode();
     73     }
     74       ln.val = vals[vals.length - 1] ?? 0;
     75       return start;
     76   }
     77 
     78 
     79 
     80 
     81 }