We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Convert Doubly Linked List to Array I

Number: 3577

Difficulty: Easy

Paid? Yes

Companies: N/A


Problem Description

Given the head of a doubly linked list, return an array containing the elements of the list in the same order.


Key Insights

  • The doubly linked list structure includes next and previous pointers, but only forward traversal (using next) is required.
  • Iterate through the list starting from the head until the end (null) is reached.
  • Append each node's value to an output array.

Space and Time Complexity

Time Complexity: O(n), where n is the number of nodes in the list.
Space Complexity: O(n), for storing the output array.


Solution

Traverse the doubly linked list starting from the head using the next pointers. For each node encountered, add its value to an output array. Continue this process until you reach the end of the list. The use of simple iteration ensures that the algorithm is both easy to understand and implement.


Code Solutions

# Definition for a doubly linked list node.
class ListNode:
    def __init__(self, val=0, next=None, prev=None):
        self.val = val
        self.next = next
        self.prev = prev

def doubly_linked_list_to_array(head):
    # Initialize an empty list to store the node values.
    output = []
    # Start traversal from the head node.
    current = head
    while current:
        # Append the current node's value to the output list.
        output.append(current.val)
        # Move to the next node.
        current = current.next
    # Return the complete output list.
    return output
← Back to All Questions