Skip to main content
Engineering LibreTexts

7.8: Linked List Traversal

  • Page ID
    34678
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    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


    This page titled 7.8: Linked List Traversal is shared under a CC BY-SA license and was authored, remixed, and/or curated by Patrick McClanahan.

    • Was this article helpful?