Insert a Node at the Beginning of a Linked List

Implement insertAtBeginning

Given the head of a singly linked list and an integer val, insert a new node holding val at the very front of the list, and return the head of the resulting list. Because a linked list is only reachable by following next pointers from its head, inserting at the front never has to touch or shift any existing node — it just needs to change what counts as the head. The optimal solution does this in O(1)O(1) — Constant TimeThe operation takes the same, small number of steps no matter how long the list is — unlike inserting at the front of an array, which must shift every existing element over., regardless of how long the list is.

Example 1:

Input: head = [2,3,4], val = 1

Output: [1,2,3,4]

Example 2:

Input: head = [], val = 5

Output: [5]

Example 3:

Input: head = [7], val = 9

Output: [9,7]

+ 5 hidden test cases run on Submit.

Constraints:

  • 0 ≤ number of nodes in head ≤ 10⁴
  • -10⁹ ≤ node value, val ≤ 10⁹
  • Do not copy or rebuild the existing nodes for the optimal solution

head =

[2, 3, 4]

val =

1