Convert Doubly Linked List to Array I - Problem

You are given the head of a doubly linked list, which contains nodes that have a next pointer and a previous pointer.

Return an integer array which contains the elements of the linked list in order.

Note: A doubly linked list allows traversal in both forward and backward directions.

Input & Output

Example 1 — Basic Case
$ Input: head = [1,2,3,4]
Output: [1,2,3,4]
💡 Note: Traverse the doubly linked list from head: 1 → 2 → 3 → 4, collect each value into array
Example 2 — Single Node
$ Input: head = [5]
Output: [5]
💡 Note: Only one node in the list, so the result array contains just that single value
Example 3 — Negative Values
$ Input: head = [-1,0,1]
Output: [-1,0,1]
💡 Note: Doubly linked list with negative, zero, and positive values: -1 → 0 → 1

Constraints

  • The number of nodes in the linked list is in the range [1, 1000]
  • -1000 ≤ Node.val ≤ 1000

Visualization

Tap to expand
Convert Doubly Linked List to Array INPUT Doubly Linked List: 1 2 3 4 next = NULL head Input: head = [1,2,3,4] Each node has prev and next pointers (doubly linked) ALGORITHM STEPS 1 Initialize Create empty result array result = [] 2 Set Current Pointer Start from head node current = head 3 Traverse and Collect While current is not NULL: result.push(current.val) current = current.next 4 Return Result Return filled array return result Time: O(n) | Space: O(n) n = number of nodes FINAL RESULT Output Array: 1 [0] 2 [1] 3 [2] 4 [3] Traversal Order: 1 --> result = [1] 2 --> result = [1,2] 3 --> result = [1,2,3] 4 --> result = [1,2,3,4] Output: [1,2,3,4] OK Key Insight: Unlike singly linked lists, doubly linked lists have both 'prev' and 'next' pointers. For this conversion, we only need the 'next' pointer to traverse forward from head to end. The 'prev' pointer enables reverse traversal but is unused here. Simple linear scan: O(n) time. TutorialsPoint - Convert Doubly Linked List to Array I | Optimal Solution
Asked in
Amazon 25 Microsoft 18
23.0K Views
Medium Frequency
~8 min Avg. Time
891 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen