You are here:

C++/linked list

Advertisement


Question
Hi, 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;


}

Answer
Hello 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

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2016 About.com. All rights reserved.