Skip to main content
Engineering LibreTexts

7.8: Linked List Traversal

  • Page ID
    34678
  • In the previous program, we have created a simple linked list with three nodes. Let us traverse the created list and print the data of each node. For traversal, let us write a general-purpose function printList() that prints any given list.

     

    // A simple C++ program for traversal of a linked list
    #include<bits/stdc++.h>
    using namespace std;
    
    
    struct Node {
        char data;
        Node* next;
    };
    
    // This function prints contents of linked list
    // starting from the given node
    void printList(Node* n)
    {
       while (n != NULL) {
         cout << n->data << " ";
         n = n->next;
       }
       cout << endl;
    }
    
    // Driver code
    int main()
    {
       Node* head = NULL;
       Node* second = NULL;
       Node* third = NULL;
    
       // allocate 3 nodes in the heap
       head = new Node();
       second = new Node();
       third = new Node();
       
       graphic depiction of 3 nodes in a linked list
    
       head->data = 'A'; // assign data in first node
       head->next = second; // Link first node with second
    
       second->data = 'B'; // assign data to second node
       second->next = third;
    
       third->data = 'C'; // assign data to third node
       third->next = NULL;
    
       printList(head);
     
       return 0;
    }
    
    Output:
     A B C

    "Linked List | Set 1 (Introduction)" by ashwani khemani is licensed under CC BY-SA 4.0