commit 08e6a1004a6aae8e31d958816b2ad56803f4b914 parent c23e5e8c6718f0be24e9a4a0ab458014ddcd600e Author: AndrewLockVI <andrewlaack1@gmail.com> Date: Mon, 15 May 2023 12:56:58 -0500 Completed reorder list problem using dart Diffstat:
| A | reorder-list/reorder-list.dart | | | 36 | ++++++++++++++++++++++++++++++++++++ |
1 file changed, 36 insertions(+), 0 deletions(-)
diff --git a/reorder-list/reorder-list.dart b/reorder-list/reorder-list.dart @@ -0,0 +1,36 @@ +//Given a singly linked list return the list where the order is +//L1,Ln,L2,Ln-1 and so on where n is the length of the list. +//The time complexity of this code is O(n) where n is the length of the list. +//My solution first creates a list of the linked list then orders it properly, +//and it finally sets the next of each node to the proper node. +//Time: 271ms Beats: 100% +//Memory: 148.2MB Beats: 66.67% +class Solution { + void reorderList(ListNode? head) { + ListNode? itr = head; + List<ListNode?> vals = []; + while(itr != null){ + vals.add(itr); + itr = itr.next; + } + List<ListNode?> return_list = []; + return_list.add(vals[0]); + + for(int i = 0 ; return_list.length < vals.length + 1; ++i){ + return_list.add(vals[i]); + return_list.add(vals[vals.length - 1 - i]); + } + + for(int i = 0 ; i < return_list.length - 1 ; ++i){ + return_list[i]?.next = return_list[i + 1]; + } + if(vals.length % 2 == 1){ + return_list[return_list.length - 2]?.next = null; + + } + else{ + return_list[return_list.length - 1]?.next = null; + } + + } +}