Bird
Raised Fist0
DSA Javaprogramming

Traversal and Printing a Linked List in DSA Java

Choose your learning style10 modes available
Mental Model
We visit each item in the list one by one from start to end to see or print its value.
Analogy: Like reading a chain of paper clips linked together, looking at each clip in order from the first to the last.
head -> 1 -> 2 -> 3 -> null
↑
Dry Run Walkthrough
Input: list: 1 -> 2 -> 3 -> null
Goal: Print all values in the list in order: 1 -> 2 -> 3 -> null
Step 1: Start at the head node with value 1
head -> [curr->1] -> 2 -> 3 -> null
Why: We begin traversal from the first node to print its value
Step 2: Print value 1 and move curr to next node
head -> 1 -> [curr->2] -> 3 -> null
Why: After printing current node, move forward to continue traversal
Step 3: Print value 2 and move curr to next node
head -> 1 -> 2 -> [curr->3] -> null
Why: Continue printing nodes in order
Step 4: Print value 3 and move curr to null (end)
head -> 1 -> 2 -> 3 -> [curr->null]
Why: Reached end of list after printing last node
Result:
1 -> 2 -> 3 -> null
Annotated Code
DSA Java
public class LinkedListTraversal {
    static class Node {
        int data;
        Node next;
        Node(int data) {
            this.data = data;
            this.next = null;
        }
    }

    public static void printList(Node head) {
        Node curr = head; // start at head
        while (curr != null) { // until end of list
            System.out.print(curr.data);
            if (curr.next != null) {
                System.out.print(" -> "); // print arrow if not last
            }
            curr = curr.next; // move to next node
        }
        System.out.print("null\n"); // end marker
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);

        printList(head); // print the list
    }
}
Node curr = head; // start at head
initialize traversal pointer at the first node
while (curr != null) { // until end of list
loop through nodes until we reach the end
System.out.print(curr.data);
print current node's value
if (curr.next != null) { System.out.print(" -> "); }
print arrow only if there is a next node
curr = curr.next; // move to next node
advance pointer to next node to continue traversal
System.out.print("null\n"); // end marker
print null to show end of list
OutputSuccess
1 -> 2 -> 3 -> null
Complexity Analysis
Time: O(n) because we visit each of the n nodes exactly once
Space: O(1) because we only use a single pointer variable regardless of list size
vs Alternative: Traversal is the simplest way to access all nodes; alternatives like recursion use extra space and are less efficient
Edge Cases
empty list (head is null)
prints only 'null' indicating no nodes
DSA Java
while (curr != null) {
single node list
prints the single node value followed by 'null'
DSA Java
if (curr.next != null) { System.out.print(" -> "); }
When to Use This Pattern
When you need to see or process every item in a linked list in order, use traversal to visit nodes one by one.
Common Mistakes
Mistake: Not checking for null before accessing node data, causing errors on empty lists
Fix: Always check if current node is null before accessing its data or next pointer
Mistake: Printing arrows after the last node, causing extra arrows in output
Fix: Print arrows only if the current node has a next node
Summary
It visits each node in the linked list from start to end and prints their values.
Use it when you want to display or process all elements in a linked list in order.
The key is to move step-by-step from one node to the next until you reach the end.

Practice

(1/5)
1. What is the main purpose of traversing a linked list in Java?
easy
A. To sort the linked list nodes automatically
B. To delete the entire linked list at once
C. To create a new linked list from scratch
D. To visit each node and perform an action like printing its value

Solution

  1. Step 1: Understand traversal meaning

    Traversal means visiting each node one by one in the linked list.
  2. Step 2: Identify traversal purpose

    Commonly, traversal is used to perform actions like printing or searching nodes.
  3. Final Answer:

    To visit each node and perform an action like printing its value -> Option D
  4. Quick Check:

    Traversal = Visit nodes [OK]
Hint: Traversal means visiting nodes one by one [OK]
Common Mistakes:
  • Confusing traversal with deletion
  • Thinking traversal creates a new list
  • Assuming traversal sorts the list
2. Which of the following is the correct syntax to start traversing a singly linked list named head in Java?
easy
A. Node current = head.next;
B. Node current = null;
C. Node current = head;
D. Node current = head.prev;

Solution

  1. Step 1: Identify starting point of traversal

    Traversal starts from the first node, which is referenced by head.
  2. Step 2: Choose correct initialization

    We assign current to head to begin traversal at the first node.
  3. Final Answer:

    Node current = head; -> Option C
  4. Quick Check:

    Start traversal at head node [OK]
Hint: Start traversal from head node reference [OK]
Common Mistakes:
  • Starting from head.next skips first node
  • Initializing current to null causes no traversal
  • Using head.prev in singly linked list causes error
3. What will be the output of the following Java code snippet?
class Node {
  int data;
  Node next;
  Node(int d) { data = d; next = null; }
}

public class Main {
  public static void main(String[] args) {
    Node head = new Node(5);
    head.next = new Node(10);
    head.next.next = new Node(15);

    Node current = head;
    while (current != null) {
      System.out.print(current.data + " -> ");
      current = current.next;
    }
    System.out.print("null");
  }
}
medium
A. 5 -> 10 -> 15 -> null
B. null -> 5 -> 10 -> 15
C. 5 10 15 null
D. 5 -> 10 -> null

Solution

  1. Step 1: Trace node creation and linking

    Nodes created with data 5, 10, 15 linked as 5 -> 10 -> 15 -> null.
  2. Step 2: Follow while loop printing

    Loop prints each node's data followed by ' -> ', then ends with 'null'.
  3. Final Answer:

    5 -> 10 -> 15 -> null -> Option A
  4. Quick Check:

    Print nodes in order with arrows [OK]
Hint: Print each node data with arrow until null [OK]
Common Mistakes:
  • Printing null at start instead of end
  • Missing arrows between nodes
  • Stopping before last node
4. Identify the error in the following code snippet for printing a linked list and select the correct fix.
Node current = head;
while (current.next != null) {
  System.out.print(current.data + " -> ");
  current = current.next;
}
System.out.print("null");
medium
A. Remove System.out.print("null") line
B. Change condition to current != null to print last node
C. Initialize current to head.next to skip first node
D. Add current = current.next inside the loop

Solution

  1. Step 1: Analyze loop condition

    The loop stops when current.next is null, so last node is not printed.
  2. Step 2: Fix condition to include last node

    Changing condition to current != null ensures last node is printed.
  3. Final Answer:

    Change condition to current != null to print last node -> Option B
  4. Quick Check:

    Loop until current is null to print all nodes [OK]
Hint: Loop until current is null to include last node [OK]
Common Mistakes:
  • Using current.next != null misses last node
  • Skipping first node by wrong initialization
  • Removing null print causes unclear output
5. Given a singly linked list, how would you modify the traversal code to print the list in reverse order without changing the list structure?
hard
A. Use recursion to traverse to the end, then print nodes on return
B. Reverse the list first, then traverse normally
C. Use a loop to print nodes from tail to head directly
D. Print nodes while moving forward, then print again backward

Solution

  1. Step 1: Understand limitation of singly linked list

    Singly linked list nodes only point forward, so backward traversal is not direct.
  2. Step 2: Use recursion to print in reverse

    Recursion goes to end first, then prints nodes on returning back, achieving reverse print without changing list.
  3. Final Answer:

    Use recursion to traverse to the end, then print nodes on return -> Option A
  4. Quick Check:

    Recursion prints reverse without modifying list [OK]
Hint: Recursion prints reverse by returning from end [OK]
Common Mistakes:
  • Trying to loop backward in singly linked list
  • Reversing list changes structure, not allowed here
  • Printing twice forward and backward duplicates output
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard