-1

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;
}
sazzad
  • 5,740
  • 6
  • 25
  • 42
  • 2
    The right tool to solve such problems is your debugger. You should step through your code line-by-line *before* asking on Stack Overflow. For more help, please read [How to debug small programs (by Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). At a minimum, you should \[edit] your question to include a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example that reproduces your problem, along with the observations you made in the debugger. – πάντα ῥεῖ Mar 08 '17 at 07:59
  • Please format your code properly (just like the samples in your C++ text book). – Jabberwocky Mar 08 '17 at 08:00

2 Answers2

2
void Insert(int x)
{
Node *temp=new Node();
temp ->data=x;
temp ->next=NULL;
if(head!=NULL)
{
temp->next=head;
head=temp;
}
}

in main program head is null so in insert function it will never update because of if(head!=NULL) check.

Correct Solution is

#include<iostream>
using namespace std;
struct Node
{
 int data;
 Node* next;
};
struct Node* head;
void Insert(int x)
{
Node *temp=new Node();
temp ->data=x;
temp ->next=NULL;
if(temp!=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;
}
Undefined Behaviour
  • 729
  • 2
  • 8
  • 27
0

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;
sazzad
  • 5,740
  • 6
  • 25
  • 42