Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 3294: Convert Doubly Linked List to Array II

LeetCode 3294 Solution Explanation

Explanation:

To convert a doubly linked list to an array, we can traverse the linked list while adding each node's value to the array. We will keep track of the head node and iterate until we reach the end of the linked list. Finally, we will return the array containing the values of the doubly linked list nodes.

  • Algorithm:

    1. Initialize an empty array to store the values of the doubly linked list nodes.
    2. Traverse the doubly linked list from the head node.
    3. For each node, add its value to the array.
    4. Return the array containing the values of the doubly linked list nodes.
  • Time Complexity: O(n) where n is the number of nodes in the doubly linked list.

  • Space Complexity: O(n) for the output array.

:

LeetCode 3294 Solutions in Java, C++, Python

public int[] convertDoublyLinkedListToArray(DoublyListNode head) {
    List<Integer> list = new ArrayList<>();
    DoublyListNode current = head;
    while (current != null) {
        list.add(current.val);
        current = current.next;
    }
    int[] result = new int[list.size()];
    for (int i = 0; i < list.size(); i++) {
        result[i] = list.get(i);
    }
    return result;
}

Interactive Code Editor for LeetCode 3294

Improve Your LeetCode 3294 Solution

Use the editor below to refine the provided solution for LeetCode 3294. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems