leetcode

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

remove-nodes-from-linked-list.dart (1334B)


      1 //Return a linked list of all nodes that do not contain a higher value on their right
      2 //To solve this I created an array of all the linked list items. I then iterated through it
      3 //from the left searching to see if a higher value on the right existed. If it did not then
      4 //it would link up to the last node found and the new node would be the head.
      5 //The time complexity of this code is O(n) where n is the number of nodes.
      6 //Time: 497ms Beats: 100%
      7 //Memory: 220.7MB Beats: 100%
      8 //This question did not have enough submissions to show
      9 //metrics, but I am confident my solution is rather fast.
     10 
     11 class Solution {
     12   ListNode? removeNodes(ListNode? head) {
     13 
     14       List<int> reverse_list = [];
     15       while(head != null){
     16           reverse_list.add(head.val);
     17           head = head.next;
     18       }
     19       int highest = 0;
     20       ListNode current = new ListNode();
     21       ListNode? last;
     22 
     23       for(int i = reverse_list.length - 1; i >= 0 ;--i){
     24         if(reverse_list[i] >= highest){
     25             highest = reverse_list[i];
     26             current = new ListNode();
     27             current.val = highest;
     28             if(last != null){
     29               current.next = last;
     30               head = current;
     31             }
     32             else{
     33               head = current;
     34             }
     35             last = current;
     36           }
     37       }
     38 
     39 
     40 
     41 
     42       return head;
     43   }
     44 }