Fundamentals/Doubly Linked Lists
← PrevNext →
Implement buildDoublyLinkedList(values) that converts an array of values into a doubly linked list and returns the head node. Each node stores three fields: data (the value), next (a pointer to the following node, or null at the tail), and prev (a pointer to the preceding node, or null at the head).
For each adjacent pair of nodes, set both pointers so the chain can be traversed forward and backward. If the input array is empty, return null.
Input
values: an array of values to place in the list, in order
Output
The head node of a doubly linked list containing the values in the same order as the input array, or null when the array is empty.
Examples
Example 1
Inputvalues = [1, 2, 3, 4, 5]
Outputnull <- 1 <-> 2 <-> 3 <-> 4 <-> 5 -> null
Explanation: Five linked nodes are created, each connected to its neighbors via next and prev pointers. The head's prev is null and the tail's next is null.
Example 2
Inputvalues = [10, 20]
Outputnull <- 10 <-> 20 -> null
Constraints
Return null when values is empty.
The head node's prev must be null and the tail node's next must be null.
For every adjacent pair (a, b), a.next must be b and b.prev must be a.