Search code examples
c++pointerslinked-listiteratorinsertion

Unable to display the values of Linked List?


Here's my C++ program which is used to insert values at the beginning of the linked list. The logic of the program seems to be fine for me but it is unable to display the values of the list. I guess the problem is in the Print() function. Please help!

#include<iostream.h>

struct Node
{
  int data;
  Node* next;
};
struct Node* head;
void Insert(int x)
{
  Node *temp=new Node();
  temp ->data=x;
  temp ->next=NULL;
  if(head!=NULL)
  {
    temp->next=head;
    head=temp;
  }
}
void Print()
{
  Node *temp=head;
  cout<<"List is:";
  do
  {
    cout<<temp->data<<"->";
    temp=temp->next;
  }while(temp!=NULL);
  cout<<endl;
}
int main()
{

  int n,i,x;
  head=NULL;
  cout<<"How many numbers \n";
  cin>>n;
  for(i=0;i<n;i++)
  {
    cout<<"Enter the number \n";
    cin>>x;
    Insert(x);
    Print();
  }
  return 0;
}

Solution

  • You need to update head which is never changed from initial NULL because of if(head!=NULL) condition checking.

    Change

        if(head!=NULL)
        {
            temp->next=head;
            head=temp;
        }
    

    to

        if(head!=NULL)
        {
            temp->next=head;
        }
        head=temp;