Build a Linked List From an Array of Values

Implement createLinkedList

A singly linked listSingly Linked ListA chain of nodes where each node stores a value and a pointer (next) to the following node. The last node's next is null. Unlike an array, nodes aren't stored contiguously in memory — the only way to reach a given node is by following next pointers from the head. is built one node at a time, connected only through each node's next pointer. Given an array of integers vals, build a singly linked list containing those values in the same order, and return its head. Each node in the list is a Node with two fields: val (the stored integer) and next (a pointer to the following node, or null if it's the last one). If vals is empty, return null — an empty list has no head.

Example 1:

Input: vals = [3,8,5]

Output: [3,8,5]

Example 2:

Input: vals = [7]

Output: [7]

Example 3:

Input: vals = []

Output: []

+ 5 hidden test cases run on Submit.

Constraints:

  • 0 ≤ vals.length ≤ 10⁴
  • -10⁹ ≤ vals[i] ≤ 10⁹
  • Build the list in the same order as the array — vals[0] becomes the head

vals =

[3, 8, 5]