Problem Description
Given an arbitrary node from a doubly linked list, return an integer array containing the elements of the list in order. Since the node is arbitrary and may not be the head, you first need to traverse backwards to find the head of the list, then iterate forward to build the resulting array.
Key Insights
- The input node can be any node in the doubly linked list, not necessarily the head.
- Use the previous pointer to backtrack to the head of the list.
- Use the next pointer from the head to traverse the entire list and build the array.
- The solution involves two passes over part or all of the list but overall remains linear in time complexity.
Space and Time Complexity
Time Complexity: O(n), where n is the number of nodes in the list. Space Complexity: O(n), as we're storing each node's value in the output array.
Solution
The solution begins by finding the head of the doubly linked list by following the "prev" pointers until a node with no previous node is reached. This gives the starting node of the list. Once the head is located, we traverse the list using the "next" pointers, appending each node’s value to an array. The final array is then returned. This approach ensures that the elements are returned in the order of the list, from head to tail.