Linked Lists Singly linked list basics
261. Traverse a Linked List
You are given head, the first node of a singly linked list. Return the values of all its nodes, in order
from the head to the last node.
A singly linked list is a chain of nodes. Each node holds a value and a pointer to the next node, and the last node's pointer is null. An empty list has no nodes, and its head is null. For an empty list, return an empty list of values.
The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 → 1 → 6. Your
function gets only the head node, not this array.
Example 1
Input: head = [7, -2, 15, 4, 0]
[7,-2,15,4,0]Explanation: The head holds 7. Its pointer leads to -2, then to 15, 4 and 0. The node holding 0 points to null, so the list ends there.
Example 2
Input: head = [3, 3, -8, 3]
[3,3,-8,3]Explanation: The value 3 sits in three nodes, and each node gives its value once, in its own place.
Example 3
Input: head = []
[]Explanation: The list is empty, so head is null and there are no values to return.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.