C++/linked list
Expert: Zlatko - 9/29/2011
QuestionHi, for some reason the data are not linking in the following code.
The purpose of the code is to take some numbers as input(-100 as termination signal) and print them serially. I can do this some other way, but I am interested to know what is the problem with this particular code.
#include<iostream>
using namespace std;
struct link{
int value;
struct link *next;
};
typedef struct link node;
int main()
{
node *head,*p,*q;
head=new node;
p=head;
while(1)
{
cin>>p->value;
if(p->value==-100)
{
p->next=NULL;
break;
}
else
{
p=p->next;
p=new node;
}
}
q=head;
while(q->next!=NULL)
{
cout<<q->value<<" ";
q=q->next;
}
return 0;
}
AnswerHello Nazmus
The problem is in the input code
else
{
p=p->next;
p=new node;
}
The program is moving off the end of the linked list so that p = null, and then p is assigned to the new node, but the new node is not connected to the list. Try using this:
else
{
p->next = new node;
p = p->next;
}
The second version creates a new node and attaches it to the linked list by putting it on the next pointer. Then it advances p so that p advances to a real node.
Best regards
Zlatko