Traversal of Linked list using C++

/******************************************
This is the basic of linked list.
In this program we will know how
Create a linked list, store value
in node and also know traversal of
linked list.
******************************************/

#include<iostream>
using namespace std;

//Declaration of Node for linked list

struct Node    
{
    int data;
    struct Node* next;
};

/*Function to print element of linked list
ptr is local node pointer variable*/

void print_linkedlist(Node* ptr){
    cout<<"Linked list elements are : "<<endl;
    while(ptr!=NULL){
        cout<<"Element is : "<<ptr->data<<endl;        //print the data
        ptr=ptr->next;        //point to next address
    }
}
int main()
{
    //Declare 3 Node type memory for linkedlist in heap
    struct Node* head;
    head=new(Node);
    Node* second=new(Node);
    Node* third=new(Node);

    //store the data and address of next node

    head->data=7;
    head->next=second;

    second->data=11;
    second->next=third;

    third->data=20;
    third->next=NULL;

    //calling function to print linked list elements

    print_linkedlist(head);

    return 0;
}

Comments