Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Last node is not printed in Linked List

I was trying to learn the Linked list and perform insertion operations from beginning of the list. while printing the nodes, the first node is not printed. Here is the core functions which I have written. Can someone help me?

struct Node //basic structure for a node
{
    ll data; //data which we want to store
    Node* link; //address of the next node;
};

Node* head=NULL;

void Insert(ll x) //insertion at beginning
{
    Node* temp=new Node();
    temp->data=x;
    temp->link=head; //we are linking new node with previously connected node
    head=temp;
}

void Print()
{
    Node* temp=head;
    while(temp->link!=NULL) //traversing the list until last element(last element.link = NULL)
    {
        cout<<temp->data<<" ";
        temp=temp->link;
    }
    cout<<endl;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);cout.tie(NULL);
    f(i,0,5)
    {
        ll x;cin>>x;
        Insert(x);
    }
    Print();
    return 0;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your Print function requires that the last node is linked or it won’t be printed. Since the last node is never linked, it will never be printed.

void Print()
{
    Node* temp = head;

    while(temp)     // <- corrected condition
    {
        std::cout << temp->data << ' ';
        temp = temp->link;
    }
    std::cout < '\n';
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading