Traversal in Linked List

Pattern: Traversal and dummy nodes

easy

Start at the head and follow next pointers until you reach null, collecting each value on the way. This walk is the base of every linked-list problem.

The problem

Given the head of a singly linked list, return all its values in order, as an array. For example, the list 5 → 6 → 7 → 8 gives [5, 6, 7, 8]. An empty list gives [].

The function name LLTraversal matches the takeUforward practice page. Use the link above for the exact statement and limits.

Think first

  • Which node can you reach directly?
  • How do you get from one node to the next?
  • How do you know you have reached the end?

Hints

    Brute force, and why it fails

    There is nothing simpler: a single walk is the only way to see the values, and it is O(n).

    The key insight

    A linked list gives you one node and a way to reach the next. Every list algorithm is some version of this walk, with extra work done at each node.

    Dry run

    50cur
    61 
    72 
    83 
    out

    The list is 5 → 6 → 7 → 8. cur starts at the head.

    Step 1 of 4

    The plan

    out = empty list
    cur = head
    while cur is not null:
        add cur.val to out
        cur = cur.next
    return out
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    Each node is visited once. Apart from the output, only cur is stored.

    Edge cases

    • Empty list: [].
    • One node: one value.
    • Repeated values are recorded each time.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<Integer> LLTraversal(ListNode head) {
            List<Integer> out = new ArrayList<>();
            for (ListNode cur = head; cur != null; cur = cur.next) out.add(cur.val);   // follow next until null
            return out;
        }
    }

    C++

    class Solution {
    public:
        vector<int> LLTraversal(ListNode* head) {
            vector<int> out;
            for (ListNode* cur = head; cur != NULL; cur = cur->next) out.push_back(cur->val);   // follow next until NULL
            return out;
        }
    };

    Python

    from lib import ListNode
    
    class Solution:
        def LLTraversal(self, head: ListNode) -> list[int]:
            out, cur = [], head
            while cur is not None:                  # follow next until None
                out.append(cur.val)
                cur = cur.next
            return out

    Common mistakes

    • Moving head itself instead of a separate cur, which loses the start if you need it later.
    • Looping while cur.next != null, which skips the last value.
    • Forgetting to move cur, which loops forever.

    Similar problems