#242Medium· asked at 6 companies
Convert Doubly Linked List to Array I
Problem
You are given the head of a doubly linked list. Each node has fields val, prev and next. Return an array containing the node values in forward order (from head to tail).
Input / Output
- Input: head node of the list (possibly
nullfor an empty list). - Output: integer array of values.
Examples
Example 1
Input: list 1 <-> 2 <-> 3 <-> 4
Output: [1, 2, 3, 4]
Example 2
Input: empty list
Output: []
Constraints
0 <= number of nodes <= 10^5-10^9 <= val <= 10^9
Approach
Traverse from the head following next pointers, appending each value:
result = []
cur = head
while cur != null:
result.append(cur.val)
cur = cur.next
return result
Because we start at the head, the prev pointers are not needed. If the array size must be known up front (fixed-size arrays), do a first pass to count nodes, allocate, then fill.
Complexity
- Time: O(n)
- Space: O(n) for the output; O(1) auxiliary.
What the interviewer is checking
- Comfort with the doubly-linked node structure and null termination.
- Handling the empty list.
- Awareness that the reverse array (tail to head) can be produced just as easily by following
prevfrom the tail — the natural lead-in to part II.
Reference solution (Python)
def dll_to_array(head):
out = []
cur = head
while cur:
out.append(cur.val)
cur = cur.next
return out
Test cases
| Input | Expected |
|---|---|
1<->2<->3<->4 | [1,2,3,4] |
empty list | [] |
single node 9 | [9] |
5<->5 | [5,5] |