c++ - cpp linked list program:error in display -
following simple doubly linked list program insert node , display linked list,
i getting error in displaying linked list,
the problem in program if add several new nodes,when select display stored linked list showing list empty, since newbie unable locate logical error,please me out,
the code follows
#include<iostream> using namespace std; class dll; class node { int data; class node *next; class node *prev; friend class dll; node(int x) { data=x; next=null; prev=null; } }; class dll { node *start; public: dll(); void insert(); void display(); }; dll::dll() { start=null; } void dll::insert() { class node *p; int no; cout<<"enter number"; cin>>no; p=new node(no); if(start==null) { p->next=null; p->prev=null; } else { p->next=start; p->prev=null; p->next->prev=p; start=p; } } void dll::display() { node *temp; temp=start; if(temp==null) { cout<<"list empty\n"; } else { while(temp!=null) { cout<<temp->data<<"\t"; temp=temp->next; } } } int main() { dll d1; int ch=1; while(ch!=3) { cout<<"enter choice\n1 insert\n2 display\n"; cin>>ch; switch(ch) { case 1:d1.insert();break; case 2:d1.display();break; default:cout<<"wrong input\n";break; } } }
while reviewing questions of stackoverflow found question , realized difficulties beginners might face , hence im adding solution mistake made me
the logical error in 'insert' function, not assigning node start , hence showing empty linked list
the solution can following
void dll::insert() { class node *p; int no; cout<<"enter number"; cin>>no; p=new node(no); if(start==null) { p->next=null; p->prev=null; start = p; //this step needs added start assigned node , not null } else { p->next=start; p->prev=null; p->next->prev=p; start=p; } }
thanks @whozcraig answer!
you never assign initial node. kind of problem sheet of paper, pencil, , 2 minutes of drawing arrows , boxes should solve, , until you're fluent in dynamic allocation used doing lot of that.
this:
if(start==null) { p->next=null; p->prev=null; // note: start still null } else { p->next=start; p->prev=null; p->next->prev=p; start=p; }
should this:
if(start==null) { p->next=null; p->prev=null; } else { p->next=start; p->prev=null; p->next->prev=p; } start=p; // note: start references last node allocated.
but worth noting constructor node
sets member pointers next
, prev
null
. therefore above code further reducible :
if (start != null) { p->next=start; start->prev=p; } start=p;
that said, real solution std::list<int>
or std:vector<int>
, suppose have start somewhere. best of luck.
Comments
Post a Comment