c++linked-listsingly-linked-listfunction-definitionnull-pointer

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

  • 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';
    }