odd-even-linked-list.dart (1274B)
1 //Given a linked list return a new linked list that 2 //is ordered with the odd indexes at the start and even indexes at 3 //the end. To do this I created two seperate lists one for even one for odd. 4 //I then passed them to a function to return a linked list based on the input 5 //array. 6 //The time complextiy is O(n) where n is the length of the linked list. 7 //Time: 241ms Beats: 100% 8 //Memory: 142.9MB Beats: 75% 9 class Solution { 10 ListNode? oddEvenList(ListNode? head) { 11 if(head == null){ 12 return head; 13 } 14 List<int> even = []; 15 List<int> odd = []; 16 while(head != null){ 17 even.add(head.val); 18 head = head.next; 19 if(head?.val != null){ 20 odd.add((head?.val ?? 0)); 21 } 22 head = head?.next; 23 } 24 return listify(even, odd); 25 } 26 ListNode listify(List<int> first , List<int> second){ 27 ListNode first_ln = new ListNode(first[0]); 28 ListNode last = first_ln; 29 for(int i = 1 ; i < first.length ; ++i){ 30 ListNode current = new ListNode(first[i]); 31 last.next = current; 32 last = current; 33 } 34 for(int i = 0 ; i < second.length ; ++i){ 35 ListNode current = new ListNode(second[i]); 36 last.next = current; 37 last = current; 38 } 39 40 return first_ln; 41 } 42 }