c++ - Inserting data in a singly link list by specifying the nth node position -
so logic goes this: suppose link list consists of (6,7,8)
data , pass insert(1,5)
,so list (5,6,7,8)
. on insert(3,2)
link list (6,7,2,8)
.
i tried compiling below code gives me error stating-
undefined reference main '-start'
i tried debugging,even searching answers found no help.kindly suggest solution.any further suggestions , bug fixes shall welcomed. (i have used codepad compiling)
#include<iostream> using namespace std; class link_no { struct node { int data; node *next; }; void insert(int n,int d,node *head) { node *temp=new node(); temp->data=d; temp->next=null; node *temp1; if(n==1) { temp->next=head; head=temp; return; } else temp1=head; { for(int i=0;i<n-1;i++) { temp1=temp1->next; } temp->next=temp1; temp1=temp; } } void print(node *start) { node *temp=start; while(temp!=null) { cout<<temp->data<<endl; temp=temp->next; } } int main() { node *head=null; link_no o1; o1.insert(1,5,head); o1.insert(2,7,head); o1.insert(1,9,head); o1.print(head); return 0; } }
the following compiles
#include<iostream> using namespace std; class link_no { private: struct node { int data; node *next; }; node *head; public: link_no(){ head = nullptr; } void insert(int n,int d) { node *temp=new node(); temp->data=d; temp->next=null; node *temp1; if(n==1) { temp->next=head; head=temp; return; } else temp1=head; { for(int i=0;i<n-1;i++) { temp1=temp1->next; } temp->next=temp1; temp1=temp; } } void print() { node *temp=head; while(temp!=null) { cout << "data " << temp->data<<endl; temp=temp->next; } } }; int main() { link_no o1; o1.insert(1,5); o1.insert(2,7); o1.insert(1,9); o1.print(); return 0; }
it not want yet prints out 5 , 9 data need debug more.
edit: suggest take paper , pen , manually try you're doing in else since there going wrong there.
if can't find out on own following works me, haven't tried testing extreme cases yet.
#include<iostream> using namespace std; class link_no { private: struct node { int data; node *next; }; node *head; public: link_no(){ head = nullptr; } void insert(int n,int d) { node *temp=new node(); temp->data=d; temp->next=null; node *temp1; if(n==1) { temp->next=head; head=temp; return; } else { cout << "foo" << endl; temp1=head; for(int i=1;i<n-1;i++) { temp1=temp1->next; } node *temp2 = temp1->next; temp1->next = temp; temp->next=temp2; } } void print() { node *temp=head; cout << "link" << endl; while(temp!=null) { cout << "data " << temp->data<<endl; temp=temp->next; } } }; int main() { link_no o1; o1.insert(1,5); o1.print(); o1.insert(2,7); o1.print(); o1.insert(1,9); o1.insert(2,6); o1.print(); return 0; }
Comments
Post a Comment