swapping-nodes-in-a-linked-list.dart (941B)
1 //Swap two nodes in a linked list without swapping the values. 2 //Basically place the kth element in the length - kth spot 3 //and vice versa not just swap the stored values. 4 //I did this using an array list where I swapped the nodes 5 //and then went through the list setting the next node to be 6 //n + 1. This was the easiest solution I could think of. 7 //The time complexity of this is O(n) where n is the lenght of the 8 //list. 9 //Time: 465ms Beats: 50% 10 //Memory: 212.2MB Beats: 25% 11 class Solution { 12 ListNode? swapNodes(ListNode? head, int k) { 13 ListNode? itr = head; 14 List<ListNode?> vals = []; 15 while(itr != null){ 16 vals.add(itr); 17 itr = itr.next; 18 } 19 20 ListNode? temp = vals[k - 1]; 21 vals[k - 1] = vals[vals.length - k]; 22 vals[vals.length - k] = temp; 23 for(int i = 0 ; i < vals.length - 1 ; ++i){ 24 vals[i]?.next = vals[i + 1]; 25 } 26 vals[vals.length - 1]?.next = null; 27 return vals[0]; 28 } 29 }