LeetCode 3294: Convert Doubly Linked List to Array II
Problem Description
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:
- Initialize an empty array to store the values of the doubly linked list nodes.
- Traverse the doubly linked list from the head node.
- For each node, add its value to the array.
- 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.
:
Solutions
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;
}
Loading editor...