LeetCode 3263: Convert Doubly Linked List to Array I Solution
Master LeetCode problem 3263 (Convert Doubly Linked List to Array I), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3263. Convert Doubly Linked List to Array I
Problem Explanation
Explanation
To convert a given doubly linked list into an array, we can simply iterate through the linked list while adding each node's value to an array. We will start from the head of the linked list and keep traversing the nodes until we reach the end. As we visit each node, we will append its value to the array. Once we have traversed the entire linked list, we will have all the node values stored in the array.
Time Complexity
The time complexity of this approach is O(n), where n is the number of nodes in the doubly linked list. We need to visit each node once to convert the linked list to an array.
Space Complexity
The space complexity is O(n) as we are storing all the node values in an array.
Solution Code
import java.util.ArrayList;
import java.util.List;
class ListNode {
int val;
ListNode prev;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public class Solution {
public int[] convertDoublyLinkedListToArray(ListNode head) {
List<Integer> result = new ArrayList<>();
ListNode current = head;
while (current != null) {
result.add(current.val);
current = current.next;
}
int[] arr = new int[result.size()];
for (int i = 0; i < result.size(); i++) {
arr[i] = result.get(i);
}
return arr;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3263 (Convert Doubly Linked List to Array I)?
This page provides optimized solutions for LeetCode problem 3263 (Convert Doubly Linked List to Array I) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3263 (Convert Doubly Linked List to Array I)?
The time complexity for LeetCode 3263 (Convert Doubly Linked List to Array I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3263 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3263 in Java, C++, or Python.