Skip to main content
Back to problems
#3294
Medium Algorithms

Convert doubly linked list to array ii

Array Linked List Doubly-Linked List
82.5% acceptance
Mar 31, 2026
10
5
You are given an arbitrary node from 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.

Solution

C++
Time O(n)
Space O(1)
LeetCode
solution.cpp
/**
 * Definition for doubly-linked list.
 * class Node {
 *     int val;
 *     Node* prev;
 *     Node* next;
 *     Node() : val(0), next(nullptr), prev(nullptr) {}
 *     Node(int x) : val(x), next(nullptr), prev(nullptr) {}
 *     Node(int x, Node *prev, Node *next) : val(x), next(next), prev(prev) {}
 * };
 */
class Solution {
public:
  vector<int> toArray(Node* node) {
    while (node->prev) {
      node = node->prev;
    }
    vector<int> result;
    while (node) {
      result.push_back(node->val);
      node = node->next;
    }
    return result;
  }
};