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.

Examples

Example 1:

1
2
Input: head = [1,2,3,4,3,2,1]
Output: [1,2,3,4,3,2,1]

Example 2:

1
2
Input: head = [2,2,2,2,2]
Output: [2,2,2,2,2]

Example 3:

1
2
Input: head = [3,2,3,2,3,2]
Output: [3,2,3,2,3,2]

Constraints:

  • The number of nodes in the given list is in the range [1, 50].
  • 1 <= Node.val <= 50

Solution

Method 1 – Simple Iteration 1

Intuition

The key idea is to traverse the doubly linked list from the head node, collecting each node’s value in order into an array. Since the list is doubly linked, we only need to follow the next pointers for this task.

Approach

  1. Initialize an empty array (or list/vector).
  2. Start from the head node.
  3. While the current node is not null:
    • Add the current node’s value to the array.
    • Move to the next node.
  4. Return the array.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
public:
    vector<int> toArray(Node* head) {
        vector<int> ans;
        while (head) {
            ans.push_back(head->val);
            head = head->next;
        }
        return ans;
    }
};
1
2
3
4
5
6
7
8
func toArray(head *Node) []int {
    ans := []int{}
    for head != nil {
        ans = append(ans, head.Val)
        head = head.Next
    }
    return ans
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
    public List<Integer> toArray(Node head) {
        List<Integer> ans = new ArrayList<>();
        while (head != null) {
            ans.add(head.val);
            head = head.next;
        }
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
    fun toArray(head: Node?): List<Int> {
        val ans = mutableListOf<Int>()
        var node = head
        while (node != null) {
            ans.add(node.`val`)
            node = node.next
        }
        return ans
    }
}
1
2
3
4
5
6
7
class Solution:
    def toArray(self, head: 'Optional[Node]') -> list[int]:
        ans: list[int] = []
        while head:
            ans.append(head.val)
            head = head.next
        return ans
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
impl Solution {
    pub fn to_array(mut head: Option<Box<Node>>) -> Vec<i32> {
        let mut ans = Vec::new();
        while let Some(node) = head {
            ans.push(node.val);
            head = node.next;
        }
        ans
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
    toArray(head: Node | null): number[] {
        const ans: number[] = [];
        while (head) {
            ans.push(head.val);
            head = head.next;
        }
        return ans;
    }
}

Complexity

  • ⏰ Time complexity: O(n), where n is the number of nodes in the list, because we visit each node exactly once.
  • 🧺 Space complexity: O(n), as we store all node values in a new array of size n.