Insert a Node at the End of a Linked List

Implement insertAtEnd

Given the head of a singly linked list and an integer val, insert a new node holding val at the very end of the list, and return the head of the resulting list. Unlike inserting at the front, appending at the end can't skip straight to the answer — a singly linked listSingly Linked ListA chain of nodes connected only through each node's next pointer, in one direction. There's no way to jump directly to the last node — the only way to find it is to follow next pointers from the head, one node at a time. only has forward next pointers, so the last node has to be located by walking from head. Once found, attaching the new node there is a single pointer write. Remember to handle the empty list: if head is null, the new node becomes the entire list.

Example 1:

Input: head = [6,2,9], val = 4

Output: [6,2,9,4]

Example 2:

Input: head = [], val = 5

Output: [5]

Example 3:

Input: head = [7], val = 9

Output: [7,9]

+ 5 hidden test cases run on Submit.

Constraints:

  • 0 ≤ number of nodes in head ≤ 10⁴
  • -10⁹ ≤ node value, val ≤ 10⁹
  • Handle the empty-list case — inserting into head = [] must return a one-node list

head =

[6, 2, 9]

val =

4