Bird
Raised Fist0
DSA Typescriptprogramming~15 mins

Traversal and Printing a Linked List in DSA Typescript - Deep Dive

Choose your learning style10 modes available
Overview - Traversal and Printing a Linked List
What is it?
A linked list is a chain of connected items called nodes. Traversal means visiting each node one by one from the start to the end. Printing a linked list means showing the values stored in each node in order. This helps us see what is inside the list.
Why it matters
Without traversal, we cannot read or use the data stored in a linked list. It would be like having a chain of boxes but never opening them to see what's inside. Traversal and printing let us check, debug, and understand the list's contents, which is essential for many programs.
Where it fits
Before learning this, you should know what a linked list is and how nodes connect. After this, you can learn how to add or remove nodes, search for values, or reverse the list.
Mental Model
Core Idea
Traversal is moving step-by-step through each connected node to access or display its value.
Think of it like...
Imagine a treasure hunt where each clue leads you to the next spot. You follow the clues one by one until you reach the end. Each clue is like a node, and following them is traversal.
Head -> [Node1(value) | next] -> [Node2(value) | next] -> [Node3(value) | next] -> null

Traversal starts at Head and moves through each next pointer until null.
Build-Up - 7 Steps
1
FoundationUnderstanding Linked List Nodes
🤔
Concept: Learn what a node is and how it stores data and a link to the next node.
A node has two parts: a value (data) and a pointer (next) to the next node. The last node points to null, meaning the list ends there. For example, a node can hold a number and a reference to the next node.
Result
You understand that nodes connect to form a chain, and the last node ends the list.
Knowing the node structure is key because traversal depends on following these next pointers.
2
FoundationStarting Point: The Head Node
🤔
Concept: The head is the first node in the list and the starting point for traversal.
The linked list keeps a reference called head that points to the first node. If head is null, the list is empty. Traversal always begins at head to visit nodes in order.
Result
You know where to start when visiting nodes in the list.
Recognizing head as the entry point prevents confusion about where to begin traversal.
3
IntermediateSimple Traversal Loop
🤔Before reading on: do you think traversal uses recursion or a loop? Commit to your answer.
Concept: Use a loop to visit each node until the end is reached.
Start with a variable current set to head. While current is not null, print current's value and move current to current.next. This repeats until current becomes null, meaning the list ended.
Result
All node values are printed in order from head to tail.
Understanding the loop stops at null helps avoid infinite loops and ensures full traversal.
4
IntermediatePrinting Node Values Clearly
🤔Before reading on: do you think printing nodes with arrows or commas is clearer? Commit to your preference.
Concept: Format the output to show the list structure visually.
Instead of printing values alone, print each value followed by '->' to show the link. For example: 1 -> 2 -> 3 -> null. This makes the list's order and end clear.
Result
Output shows the linked list as a chain of values ending with null.
Visual formatting helps quickly understand the list's shape and contents.
5
IntermediateHandling Empty Lists Gracefully
🤔
Concept: Check if the list is empty before traversal to avoid errors.
If head is null, print 'List is empty' instead of trying to traverse. This prevents null reference errors and informs the user clearly.
Result
Empty lists are handled without crashes and with clear messages.
Knowing to check for empty lists prevents runtime errors and improves user experience.
6
AdvancedRecursive Traversal Approach
🤔Before reading on: do you think recursion is simpler or more complex than loops for traversal? Commit to your opinion.
Concept: Use a function that calls itself to visit nodes one by one.
Define a function that takes a node. If the node is null, print 'null' and return. Otherwise, print the node's value and call the function again with node.next. This visits nodes in order recursively.
Result
The list is printed in order using recursion, ending with null.
Understanding recursion offers an alternative traversal method and deepens grasp of function calls.
7
ExpertAvoiding Infinite Loops in Cyclic Lists
🤔Before reading on: do you think traversal always ends at null? Commit to yes or no.
Concept: Detect cycles to prevent endless traversal loops.
If a linked list has a cycle (a node points back to an earlier node), traversal loops forever. To avoid this, keep track of visited nodes or use two pointers moving at different speeds to detect cycles before printing.
Result
Traversal safely ends even if the list has cycles, avoiding infinite loops.
Knowing cycle detection is crucial for robust traversal in real-world linked lists.
Under the Hood
Traversal works by following the next pointer inside each node. The program keeps a reference to the current node and moves it forward by reading current.next. This continues until current becomes null, signaling the list's end. Each step accesses the node's value and then moves on.
Why designed this way?
Linked lists use pointers to connect nodes because arrays need continuous memory, which can be hard to find. Traversal follows these pointers because nodes are scattered in memory. This design trades direct access speed for flexible memory use and easy insertion/removal.
Head
 │
 ▼
[Node1(value) | next]──▶[Node2(value) | next]──▶[Node3(value) | next]──▶null

Traversal:
Current = Head
While Current != null:
  Access Current.value
  Current = Current.next
Myth Busters - 4 Common Misconceptions
Quick: Does traversal always end when current.next is null? Commit yes or no.
Common Belief:Traversal ends when current.next is null.
Tap to reveal reality
Reality:Traversal ends when current itself is null, not current.next. The last node's next is null, so after visiting the last node, current moves to null and stops.
Why it matters:Stopping too early misses the last node's value, causing incomplete traversal.
Quick: Can you traverse a linked list backwards easily? Commit yes or no.
Common Belief:You can easily traverse a singly linked list backwards by following pointers.
Tap to reveal reality
Reality:Singly linked lists only have next pointers, so you cannot go backwards without extra work or data structures.
Why it matters:Assuming backward traversal is easy leads to wrong code and bugs.
Quick: Does printing node values change the list structure? Commit yes or no.
Common Belief:Printing node values modifies the linked list.
Tap to reveal reality
Reality:Traversal and printing only read node values; they do not change the list or pointers.
Why it matters:Misunderstanding this can cause unnecessary worries about side effects.
Quick: Can traversal get stuck in an infinite loop if the list has a cycle? Commit yes or no.
Common Belief:Traversal always ends because lists have an end.
Tap to reveal reality
Reality:If the list has a cycle, traversal loops forever unless cycle detection is used.
Why it matters:Ignoring cycles can crash programs or freeze them.
Expert Zone
1
Traversal performance depends on list length; knowing this helps optimize algorithms that use traversal repeatedly.
2
Recursive traversal uses call stack memory, which can cause stack overflow on very long lists; iterative traversal avoids this.
3
Cycle detection algorithms like Floyd's Tortoise and Hare are often combined with traversal to ensure safety.
When NOT to use
Traversal is not suitable when you need random access to nodes; arrays or other data structures are better. Also, avoid naive traversal on cyclic lists without cycle detection.
Production Patterns
In real systems, traversal is used for printing logs, searching values, or applying functions to each node. Cycle detection is standard in network or graph-like linked structures to prevent infinite loops.
Connections
Tree Traversal
Traversal in linked lists is a simpler form of tree traversal, visiting nodes in a sequence.
Understanding linear traversal helps grasp more complex tree traversals like preorder or inorder.
Graph Cycle Detection
Cycle detection in linked lists uses similar ideas as detecting cycles in graphs.
Knowing graph algorithms enriches understanding of safe traversal in linked structures.
Supply Chain Management
Traversal is like following a supply chain from raw materials to finished product step-by-step.
Seeing traversal as a process flow helps appreciate the importance of order and completeness.
Common Pitfalls
#1Forgetting to move to the next node inside the loop causes infinite loops.
Wrong approach:let current = head; while (current !== null) { console.log(current.value); // missing current = current.next; }
Correct approach:let current = head; while (current !== null) { console.log(current.value); current = current.next; }
Root cause:Not updating the current pointer means the loop never progresses, causing an endless loop.
#2Trying to traverse an empty list without checking for null head causes errors.
Wrong approach:let current = head; console.log(current.value); // Error if head is null
Correct approach:if (head === null) { console.log('List is empty'); } else { let current = head; while (current !== null) { console.log(current.value); current = current.next; } }
Root cause:Assuming the list always has nodes leads to null reference errors.
#3Printing nodes without indicating the end confuses the output.
Wrong approach:let current = head; while (current !== null) { process.stdout.write(current.value + ' '); current = current.next; } // No indication of list end
Correct approach:let current = head; while (current !== null) { process.stdout.write(current.value + ' -> '); current = current.next; } console.log('null');
Root cause:Not showing the list end makes it unclear where the list stops.
Key Takeaways
Traversal means visiting each node in a linked list one by one, starting from the head.
You must follow the next pointers until you reach null to visit all nodes.
Printing nodes with arrows and ending with null clearly shows the list structure.
Always check if the list is empty before traversal to avoid errors.
Detect cycles in lists to prevent infinite loops during traversal.

Practice

(1/5)
1. What does it mean to traverse a linked list?
easy
A. Visit each node in the list one by one from start to end
B. Add a new node at the end of the list
C. Delete the first node of the list
D. Reverse the order of nodes in the list

Solution

  1. Step 1: Understand traversal meaning

    Traversal means going through each element in order to access or process it.
  2. Step 2: Apply to linked list context

    In a linked list, traversal means visiting each node starting from the head until the end (null).
  3. Final Answer:

    Visit each node in the list one by one from start to end -> Option A
  4. Quick Check:

    Traversal = Visit nodes sequentially [OK]
Hint: Traversal means visiting nodes one after another [OK]
Common Mistakes:
  • Confusing traversal with insertion or deletion
  • Thinking traversal changes the list order
  • Assuming traversal skips nodes
2. Which of the following is the correct way to start traversing a linked list in TypeScript?
easy
A. let current = head;
B. let current = tail;
C. let current = null;
D. let current = new Node();

Solution

  1. Step 1: Identify starting point for traversal

    Traversal starts from the first node, called head, to visit all nodes.
  2. Step 2: Check options for correct initialization

    Setting current to head allows moving through nodes; tail or null won't start traversal properly.
  3. Final Answer:

    let current = head; -> Option A
  4. Quick Check:

    Start traversal at head node [OK]
Hint: Always start traversal from the head node [OK]
Common Mistakes:
  • Starting traversal from tail which is the last node
  • Initializing current to null which skips traversal
  • Creating a new node instead of using existing head
3. What will be the output of the following TypeScript code that prints a linked list?
class Node {
  value: number;
  next: Node | null;
  constructor(value: number) {
    this.value = value;
    this.next = null;
  }
}

const head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);

let current = head;
while (current !== null) {
  console.log(current.value);
  current = current.next;
}
medium
A. 3 2 1
B. 1 2 3
C. 1 3 2
D. 2 3 1

Solution

  1. Step 1: Understand list structure

    The list nodes are linked as 1 -> 2 -> 3 -> null.
  2. Step 2: Trace the while loop output

    The loop prints current.value starting at head (1), then moves to 2, then 3, then stops at null.
  3. Final Answer:

    1 2 3 -> Option B
  4. Quick Check:

    Print nodes in order: 1 2 3 [OK]
Hint: Print values while moving from head to next until null [OK]
Common Mistakes:
  • Printing in reverse order by mistake
  • Skipping nodes by incorrect pointer update
  • Confusing node values order
4. Identify the error in this linked list traversal code and select the fix:
let current = head;
while (current.next !== null) {
  console.log(current.value);
  current = current.next;
}
medium
A. Remove console.log inside the loop
B. Add console.log after the loop
C. Initialize current to null
D. Change condition to current !== null

Solution

  1. Step 1: Analyze loop condition

    The loop stops when current.next is null, so it skips printing the last node.
  2. Step 2: Fix condition to include last node

    Changing condition to current !== null ensures all nodes, including last, are printed.
  3. Final Answer:

    Change condition to current !== null -> Option D
  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
  • Not updating current inside loop causes infinite loop
  • Printing after loop instead of inside
5. Given a linked list with nodes containing values 5 -> 10 -> 15 -> null, write a TypeScript function to traverse and collect these values into an array. What will be the returned array after traversal?
hard
A. [15, 10, 5]
B. [5, 15, 10]
C. [5, 10, 15]
D. [10, 5, 15]

Solution

  1. Step 1: Traverse from head to end

    Start at head (5), then move to 10, then 15, collecting values in order.
  2. Step 2: Collect values in array during traversal

    Push each node's value into an array as you visit it, resulting in [5, 10, 15].
  3. Final Answer:

    [5, 10, 15] -> Option C
  4. Quick Check:

    Values collected in order visited [OK]
Hint: Collect values while traversing from head to null [OK]
Common Mistakes:
  • Collecting values in reverse order
  • Skipping nodes by wrong pointer update
  • Returning array before traversal completes
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