leetcode

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

reorder-list.dart (1138B)


      1 //Given a singly linked list return the list where the order is
      2 //L1,Ln,L2,Ln-1 and so on where n is the length of the list.
      3 //The time complexity of this code is O(n) where n is the length of the list.
      4 //My solution first creates a list of the linked list then orders it properly,
      5 //and it finally sets the next of each node to the proper node.
      6 //Time: 271ms Beats: 100%
      7 //Memory: 148.2MB Beats: 66.67%
      8 class Solution {
      9   void reorderList(ListNode? head) {
     10       ListNode? itr = head;
     11       List<ListNode?> vals = [];
     12       while(itr != null){
     13           vals.add(itr);
     14           itr = itr.next;
     15       }
     16       List<ListNode?> return_list = [];
     17       return_list.add(vals[0]);
     18 
     19       for(int i = 0 ; return_list.length < vals.length + 1; ++i){
     20         return_list.add(vals[i]);
     21         return_list.add(vals[vals.length - 1 - i]);
     22       }
     23 
     24       for(int i = 0 ; i < return_list.length - 1 ; ++i){
     25         return_list[i]?.next = return_list[i + 1];
     26       }
     27       if(vals.length % 2 == 1){
     28         return_list[return_list.length - 2]?.next = null;
     29 
     30       }
     31       else{
     32         return_list[return_list.length - 1]?.next = null;
     33       }
     34 
     35   }
     36 }