leetcode

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

reverse-linked-list-ii.dart (1641B)


      1 //Reverse the nodes between the left and right points of a linked list.
      2 //To do this I put all of the nodes into an array and then using that array I created 
      3 //a subarray of all the values between the left and the right nodes. Then I iterated through
      4 //the list backwards to place them back into the original array. From there I turned the array
      5 //into a linked list and returned it. Despite the number of steps this algorithm is still O(n) time 
      6 //complexity where n is the number of nodes in the list.
      7 //Time: 260ms Beats: 80%
      8 //Memory: 142.7MB Beats: 80%
      9 
     10 /**
     11  * Definition for singly-linked list.
     12  * class ListNode {
     13  *   int val;
     14  *   ListNode? next;
     15  *   ListNode([this.val = 0, this.next]);
     16  * }
     17  */
     18 class Solution {
     19   ListNode? reverseBetween(ListNode? head, int left, int right) {
     20       List<int> vals = [];
     21       while(head != null){
     22         vals.add(head.val);
     23         head = head.next;
     24       }
     25       List<int> between_list = [];
     26       int diff = right - left;
     27       for(int i = left - 1 ; i <= left - 1 + diff ; ++i){
     28         between_list.add(vals[i]);
     29       }
     30       int counter = 0;
     31       for(int i = right - 1 ; i >= left - 1 ; --i){
     32           vals[i] = between_list[counter];
     33           counter += 1;
     34       }
     35       ListNode? last;
     36       ListNode? first;
     37       for(int i = 0 ; i < vals.length ; ++i){
     38         if(first == null){
     39             first = new ListNode();
     40             first.val = vals[i];
     41             last = first;
     42         }
     43         else{
     44           ListNode current = new ListNode();
     45           current.val = vals[i];
     46           last?.next = current;
     47           last = current;
     48         }
     49       }
     50       return first;
     51   }
     52 }