leetcode

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

swap-nodes.dart (917B)


      1 //Swap every other node in a list then return the head.
      2 //I did this the easy way by putting them into an array swapping
      3 //them and setting the next val to the next.
      4 //The time complexity if O(n) where n is the lenght of the list.
      5 //Time: 258ms Beats: 77.78% 
      6 //Memory: 144.5MB Beats: 22.22%
      7 class Solution {
      8   ListNode? swapPairs(ListNode? head) {
      9       if(head == null || head?.next == null){
     10           return head;
     11       }
     12       List<ListNode?> nodes = [];
     13       while(head != null){
     14           nodes.add(head);
     15           head = head.next;
     16       }
     17       int itr = 0;
     18       while(itr < nodes.length - 1){
     19           ListNode? temp = nodes[itr];
     20           nodes[itr] = nodes[itr + 1];
     21           nodes[itr + 1] = temp;
     22           itr += 2;
     23       }
     24       for(int i = 0 ; i < nodes.length - 1; ++i){
     25           nodes[i]?.next = nodes[i + 1];
     26       }
     27       nodes[nodes.length - 1]?.next = null;
     28       return nodes[0];
     29   }
     30 }