oneby7

Linked Lists Singly linked list basics

261. Traverse a Linked List

Easy

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

7-21540

Input: head = [7, -2, 15, 4, 0]

Output: [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

33-83

Input: head = [3, 3, -8, 3]

Output: [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 = []

Output: []

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.

head = [6, 1, 9, 2]

Constraints

  • 0 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.