Bird
Raised Fist0
DSA Cprogramming

Traversal Forward and Backward in DSA C

Choose your learning style10 modes available
Mental Model
Traversal means visiting each item in a list one by one, either from start to end or from end to start.
Analogy: Imagine walking through a row of houses on a street. Walking forward means going from the first house to the last, and walking backward means going from the last house back to the first.
Head -> 1 ↔ 2 ↔ 3 ↔ 4 -> null
↑
Current position at head
Dry Run Walkthrough
Input: Doubly linked list: 1 ↔ 2 ↔ 3 ↔ 4, traverse forward then backward
Goal: Visit all nodes from start to end, then from end back to start
Step 1: Start at head node with value 1
1 [curr↑] ↔ 2 ↔ 3 ↔ 4 -> null
Why: We begin traversal at the first node
Step 2: Move forward to node with value 2
1 ↔ 2 [curr↑] ↔ 3 ↔ 4 -> null
Why: Visit next node in forward direction
Step 3: Move forward to node with value 3
1 ↔ 2 ↔ 3 [curr↑] ↔ 4 -> null
Why: Continue forward traversal
Step 4: Move forward to node with value 4 (tail)
1 ↔ 2 ↔ 3 ↔ 4 [curr↑] -> null
Why: Reached last node in forward traversal
Step 5: Start backward traversal from tail node 4
1 ↔ 2 ↔ 3 ↔ 4 [curr↑] -> null
Why: Begin visiting nodes backward from last node
Step 6: Move backward to node with value 3
1 ↔ 2 ↔ 3 [curr↑] ↔ 4 -> null
Why: Visit previous node in backward direction
Step 7: Move backward to node with value 2
1 ↔ 2 [curr↑] ↔ 3 ↔ 4 -> null
Why: Continue backward traversal
Step 8: Move backward to node with value 1 (head)
1 [curr↑] ↔ 2 ↔ 3 ↔ 4 -> null
Why: Reached first node in backward traversal
Result:
Forward traversal: 1 -> 2 -> 3 -> 4 -> null
Backward traversal: 4 -> 3 -> 2 -> 1 -> null
Annotated Code
DSA C
#include <stdio.h>
#include <stdlib.h>

// Node structure for doubly linked list
typedef struct Node {
    int data;
    struct Node* next;
    struct Node* prev;
} Node;

// Create a new node with given data
Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;
    newNode->prev = NULL;
    return newNode;
}

// Append node at the end
void append(Node** head_ref, int data) {
    Node* newNode = createNode(data);
    if (*head_ref == NULL) {
        *head_ref = newNode;
        return;
    }
    Node* temp = *head_ref;
    while (temp->next != NULL) {
        temp = temp->next; // advance temp to last node
    }
    temp->next = newNode; // link last node to new node
    newNode->prev = temp; // link new node back to last node
}

// Traverse forward from head
void traverseForward(Node* head) {
    Node* curr = head;
    while (curr != NULL) {
        printf("%d -> ", curr->data); // print current node data
        curr = curr->next; // move forward
    }
    printf("null\n");
}

// Traverse backward from tail
void traverseBackward(Node* tail) {
    Node* curr = tail;
    while (curr != NULL) {
        printf("%d -> ", curr->data); // print current node data
        curr = curr->prev; // move backward
    }
    printf("null\n");
}

int main() {
    Node* head = NULL;
    append(&head, 1);
    append(&head, 2);
    append(&head, 3);
    append(&head, 4);

    printf("Forward traversal: ");
    traverseForward(head);

    // Find tail for backward traversal
    Node* tail = head;
    while (tail->next != NULL) {
        tail = tail->next; // advance to last node
    }

    printf("Backward traversal: ");
    traverseBackward(tail);

    return 0;
}
while (temp->next != NULL) { temp = temp->next; // advance temp to last node }
advance temp to last node to append new node at end
temp->next = newNode; // link last node to new node newNode->prev = temp; // link new node back to last node
connect new node forward and backward pointers
while (curr != NULL) { printf("%d -> ", curr->data); // print current node data curr = curr->next; // move forward }
traverse forward visiting each node
while (curr != NULL) { printf("%d -> ", curr->data); // print current node data curr = curr->prev; // move backward }
traverse backward visiting each node
while (tail->next != NULL) { tail = tail->next; // advance to last node }
find tail node to start backward traversal
OutputSuccess
Forward traversal: 1 -> 2 -> 3 -> 4 -> null Backward traversal: 4 -> 3 -> 2 -> 1 -> null
Complexity Analysis
Time: O(n) because we visit each node once in forward and once in backward traversal
Space: O(1) because traversal uses only a few pointers, no extra storage proportional to n
vs Alternative: Compared to singly linked list, backward traversal is not possible without extra memory or reversing the list
Edge Cases
Empty list
Traversal prints 'null' immediately without errors
DSA C
if (*head_ref == NULL) { *head_ref = newNode; return; }
Single node list
Forward and backward traversal print the single node value once
DSA C
while (temp->next != NULL) { temp = temp->next; }
When to Use This Pattern
When you need to visit elements in both directions efficiently, use a doubly linked list traversal pattern.
Common Mistakes
Mistake: Trying to traverse backward in a singly linked list without extra memory
Fix: Use a doubly linked list or store nodes in a stack to simulate backward traversal
Summary
Visits each node forward from head to tail, then backward from tail to head in a doubly linked list.
Use when you need to move through data in both directions easily.
The key is that each node links to both next and previous nodes, allowing forward and backward moves.

Practice

(1/5)
1. What does forward traversal in a linked list mean?
easy
A. Visiting nodes from the first node to the last node
B. Visiting nodes from the last node to the first node
C. Skipping every alternate node while visiting
D. Visiting nodes randomly

Solution

  1. Step 1: Understand forward traversal

    Forward traversal means starting at the first node and moving to the next node repeatedly until the end.
  2. Step 2: Compare with options

    Only Visiting nodes from the first node to the last node describes visiting nodes from first to last, which matches forward traversal.
  3. Final Answer:

    Visiting nodes from the first node to the last node -> Option A
  4. Quick Check:

    Forward traversal = first to last [OK]
Hint: Forward means start to end in order [OK]
Common Mistakes:
  • Confusing forward with backward traversal
  • Thinking traversal is random
  • Assuming skipping nodes is traversal
2. Which of the following is the correct syntax to traverse a singly linked list forward in C?
easy
A. for(Node* curr = head; curr != NULL; curr = curr->prev) { /* process curr */ }
B. for(Node* curr = head; curr != NULL; curr = curr->next) { /* process curr */ }
C. while(head != NULL) { head = head->prev; }
D. for(Node* curr = tail; curr != NULL; curr = curr->prev) { /* process curr */ }

Solution

  1. Step 1: Identify forward traversal syntax

    Forward traversal in singly linked list uses next pointer starting from head.
  2. Step 2: Check options for correct pointer usage

    for(Node* curr = head; curr != NULL; curr = curr->next) { /* process curr */ } uses curr = curr->next starting from head, which is correct.
  3. Final Answer:

    for(Node* curr = head; curr != NULL; curr = curr->next) { /* process curr */ } -> Option B
  4. Quick Check:

    Use next pointer from head for forward traversal [OK]
Hint: Use next pointer from head for forward traversal [OK]
Common Mistakes:
  • Using prev pointer in singly linked list
  • Starting from tail in singly linked list
  • Using incorrect loop conditions
3. What will be the output of the following code snippet that traverses a doubly linked list backward?
typedef struct Node {
  int data;
  struct Node* next;
  struct Node* prev;
} Node;

void printBackward(Node* tail) {
  Node* curr = tail;
  while(curr != NULL) {
    printf("%d ", curr->data);
    curr = curr->prev;
  }
}

// List: 1 <-> 2 <-> 3, tail points to node with data 3
printBackward(tail);
medium
A. 1 2 3
B. 3 1 2
C. 3 2 1
D. 2 3 1

Solution

  1. Step 1: Understand backward traversal in doubly linked list

    Starting from tail (3), moving prev pointer visits nodes 3, 2, then 1.
  2. Step 2: Trace the output

    Prints 3, then 2, then 1 with spaces.
  3. Final Answer:

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

    Backward traversal prints tail to head [OK]
Hint: Backward traversal prints from tail to head [OK]
Common Mistakes:
  • Confusing order of printing
  • Using next pointer instead of prev
  • Starting from head instead of tail
4. Identify the error in the following code that attempts to traverse a doubly linked list backward:
void traverseBackward(Node* tail) {
  Node* curr = tail;
  while(curr->next != NULL) {
    printf("%d ", curr->data);
    curr = curr->prev;
  }
}
medium
A. The printf statement is missing a newline character
B. The pointer curr should start from head, not tail
C. The code should use curr = curr->next instead of curr = curr->prev
D. The loop condition should check curr != NULL, not curr->next != NULL

Solution

  1. Step 1: Analyze loop condition for backward traversal

    Backward traversal moves using prev pointer until curr becomes NULL.
  2. Step 2: Identify incorrect condition

    Checking curr->next != NULL is wrong; it should be curr != NULL to avoid null pointer access.
  3. Final Answer:

    The loop condition should check curr != NULL, not curr->next != NULL -> Option D
  4. Quick Check:

    Loop until curr is NULL in backward traversal [OK]
Hint: Check curr != NULL in loops, not curr->next for backward traversal [OK]
Common Mistakes:
  • Using next pointer condition in backward traversal
  • Starting from head instead of tail
  • Ignoring null pointer checks
5. Given a doubly linked list with nodes containing integers, write a function to print the list forward and then backward without using extra space. Which approach correctly achieves this?
hard
A. Traverse from head to tail printing data, then traverse from tail to head printing data
B. Traverse from head to tail printing data twice
C. Traverse from tail to head printing data, then traverse from head to tail printing data
D. Traverse from head to tail printing data, then reverse the list and print forward again

Solution

  1. Step 1: Understand traversal without extra space

    Use existing next and prev pointers to traverse forward and backward.
  2. Step 2: Identify correct approach

    Traverse from head to tail printing data, then traverse from tail to head printing data correctly traverses forward from head to tail, then backward from tail to head printing data without modifying list.
  3. Final Answer:

    Traverse from head to tail printing data, then traverse from tail to head printing data -> Option A
  4. Quick Check:

    Use head and tail pointers for forward and backward traversal [OK]
Hint: Print forward from head, backward from tail without changing list [OK]
Common Mistakes:
  • Reversing list unnecessarily
  • Printing forward twice
  • Using extra space like arrays or stacks
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