Linked List Values

Linked List Values

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).

Examples

1 → 2 → 3   // → [1, 2, 3]
9           // → [9]
(empty)     // → []

Walkthrough

Thinking it through

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.

Building the approach

  1. Create an empty collection to gather results into.
  2. Start a pointer at the head.
  3. While the pointer points to a real node, add its value to the collection, then move the pointer forward.
  4. When the pointer runs off the end, the collection holds every value in the order they appeared.

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.

Why order comes out right automatically

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.

The empty list

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.

Why not something more complex?

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.

Where this generalizes

"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.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.