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
p=p->next;    
p=new node;

The pointer p is being lost here.


p->next = new node;
p = p->next ;

should be fine.



#include <iostream>

int main()
{
   struct link { int value ; link* next ; link( int v ) : value(v), next(0) {} } ;

   link* head = 0 ;
   link* tail = 0 ;

   int v ;
   while( std::cout << '?' && std::cin >> v && v != -100 )
   {
       if( head == 0 ) head = tail = new link(v) ;
       else { tail->next = new link(v) ; tail = tail->next ; }
   }

   for( link* p = head ; p != 0 ; p = p->next) std::cout << p->value << ' ' ;
   std::cout << '\n' ;
}

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.