Fundamentals/Nodes and Pointers
← PrevNext →
Implement buildLinkedList(values) that converts an array of values into a singly linked list and returns the head node. Each node has two fields: data (the value at that position) and next (a reference to the next node, or null at the end of the list).
The i-th node in the resulting chain stores values[i], and the final node's next pointer is null. If the input array is empty, return null because there is no head node to return.
Input
values: an array of values to place in the list, in order
Output
The head node of a singly 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]
Output1 -> 2 -> 3 -> 4 -> 5 -> null
Explanation: Five linked nodes are created, one per array element, with the last node's next pointer set to null.
Example 2
Inputvalues = [10, 20]
Output10 -> 20 -> null
Constraints
Return null when values is empty.
The last node's next pointer must be null.
Node order must match the order of values.