Return a slice containing the values of a linked list, in order from head to tail.
linkedListValues(head)
Input format: space-separated node values. Output the collected values, space-separated (empty line for the empty list).
1 → 2 → 3 // → [1, 2, 3]
9 // → [9]
(empty) // → []
This is the same traversal as counting nodes, except instead of throwing away the value at each step, you keep it. Every linked-list problem starts with the same question: "can I answer this by visiting each node once, in order, doing something small at each stop?" Here, that something is: record the value.
You're moving strictly forward, only ever looking at the current node — no second pointer, no lookahead, no need to know the length in advance.
A singly linked list only moves one direction, so a straightforward forward traversal naturally visits nodes head-to-tail. Appending to your output as you go preserves that order — no extra reordering needed.
If the head is already the end marker, the loop never runs, and you return the empty collection you started with. Same pattern as list-length: structure the loop around "while there's a current node," and edge cases resolve themselves.
You could reach for recursion here (process the head, then recurse on the rest), since linked lists have a naturally recursive structure. That works too, but for simple accumulation, iteration is easier to reason about and avoids call-stack space proportional to the list's length — the only memory that grows is the output itself, which you need anyway.
"Visit each node, extract or transform something, append to a result" is the backbone of a huge number of linked-list tasks — turning a list into an array, building a new list with transformed values, filtering nodes by a condition. Once this loop shape is second nature, most read-only linked-list problems are just deciding what goes inside the loop body.
def linked_list_values(head):
vals = []
node = head
while node is not None:
vals.append(node.val)
node = node.next
return vals
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.