leetcode

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

reverse-list.dart (1099B)


      1 //This algorithm reverses the order of a linked list.
      2 //To do this it puts all of the values into a list and then
      3 //iterates through the list in reverse order placing each iterated value
      4 //into a new linked list. From there it returns that head of the new list.
      5 //The time complexity of this is O(n) where n is the length of the list.
      6 //Runtime: 239ms Beats: 93.94%
      7 //Memory: 142.5MB Beats: 77.78%
      8 
      9 /**
     10  * Definition for singly-linked list.
     11  * class ListNode {
     12  *   int val;
     13  *   ListNode? next;
     14  *   ListNode([this.val = 0, this.next]);
     15  * }
     16  */
     17 class Solution {
     18   ListNode? reverseList(ListNode? head) {
     19     if(head == null){
     20       return null;
     21     }
     22 
     23       List<ListNode?> nodes = [];
     24       while(head != null){
     25         nodes.add(head);
     26         head = head.next;
     27       }
     28       ListNode? ln1 = new ListNode();
     29       ln1.val = nodes[nodes.length - 1]?.val ?? 0;
     30       head = ln1;
     31       ListNode? ln2;
     32       for(int i = nodes.length - 2 ; i >= 0 ; --i){
     33         ln2 = new ListNode();
     34         ln2.val = nodes[i]?.val ?? 0;
     35         ln1?.next = ln2;
     36         ln1 = ln2;
     37       }
     38       return head;
     39   }
     40 }