c++ linked list pointer segmentation fault -
i getting segmentation fault code below when program reaches addnode() function. don't know if there issues elsewhere since flow not going forward
#include<iostream> using namespace std; struct node { int value; node *next; }; node *head; void addnode(int); void destroytree(); int main() { head=new node; head=null; int no,ch=1; while(ch!=0) { cout<<"enter choice (0 exit, 1 enter): "; cin>>ch; if(ch==0) break; cout<<"enter no: "; cin>>no; addnode(no); } cout<<"\ntime print.\n\n"; destroytree(); cout<<endl; return 0; } void addnode(int no) { node *n=new node; node *trav; trav=head; while(trav!=null && trav->next!=null) { trav=trav->next; } if(trav==null) { trav->value=no; trav->next=null; return; } n->value=no; n->next=null; trav->next=n; } void destroytree() { node *n; while(head!=null) { n=head; cout<<head->value<<"->next ** "; head=head->next; delete n; } }
classes not allowed. want 'head' point start of list in cases except destroytree(). add node end of list, start 'head' , move on till next null. destroy tree, print first element delete it. print next element , delete till node->next null
you dereferencing null pointer doesn't make sense. repeating in code below maybe you're not thinking through you're doing.
if(trav==null) { trav->value=no; trav->next=null; return; } n->value=no; n->next=null; trav->next=n;
apart assigning values node, you're looking drop new node end of list. if didn't find traversing list it's because list empty end of list head.
n->value=no; n->next=null; (trav != null ? trav->next : head) = n;
Comments
Post a Comment