Convert Array to Doubly Linked List
Pattern: Doubly and circular lists
Walk the array once, creating a node for each value. Link each new node to the current tail in both directions, then make it the tail.
The problem
Given an array, build a doubly linked list holding its values in the same order and return the head. Every node's
prev must point to the node before it, and the head's prev is null. For example, [1, 2, 3, 4, 5] gives
1 ⇄ 2 ⇄ 3 ⇄ 4 ⇄ 5.
The function name arrayToDoublyLinkedList matches the takeUforward practice page. Use the link above for the exact
statement and limits. In this guide's code the node type is DNode, with val, prev and next. The tests check
every prev link, not only the values.
Think first
- Which node do you need to remember while building?
- Which two pointers does each new node need set?
- What does an empty array give?
Hints
Brute force, and why it fails
There is no shorter way: each value needs one node and two links. One pass is O(n).
The key insight
Building a doubly linked list is the singly-linked build plus one more link per node, always made in the same step as the forward link.
Dry run
| list | empty |
|---|
arr = [1, 2, 3]. The list starts empty.
The plan
head = null, tail = null
for each v in arr:
node = new DNode(v)
if head is null: head = node
else: tail.next = node; node.prev = tail
tail = node
return head
Complexity
- Time
O(n)- Space
O(1)
One node per value; apart from the list itself, only two pointers are kept.
Edge cases
- Empty array: null.
- One value: a node with both pointers null.
- Repeated values: separate nodes.
I've built my logic, show the code
Java
class Solution {
public DNode arrayToDoublyLinkedList(int[] arr) {
DNode head = null, tail = null;
for (int v : arr) {
DNode node = new DNode(v);
if (head == null) head = node; // the first node is the head
else {
tail.next = node; // link forwards
node.prev = tail; // and backwards
}
tail = node;
}
return head;
}
}C++
class Solution {
public:
DNode* arrayToDoublyLinkedList(vector<int>& arr) {
DNode *head = NULL, *tail = NULL;
for (int v : arr) {
DNode* node = new DNode(v);
if (head == NULL) head = node; // the first node is the head
else {
tail->next = node; // link forwards
node->prev = tail; // and backwards
}
tail = node;
}
return head;
}
};Python
from lib import DNode
class Solution:
def arrayToDoublyLinkedList(self, arr: list[int]) -> DNode:
head = tail = None
for v in arr:
node = DNode(v)
if head is None:
head = node # the first node is the head
else:
tail.next = node # link forwards
node.prev = tail # and backwards
tail = node
return headCommon mistakes
- Setting
nextbut notprev. - Forgetting to move
tail, so every node links to the first. - Giving the head a non-null
prev.