c++ - I always run into a infinite loop on running this program. -


this code insertion of node in linked list after value/data of "2" found in list.

#include<iostream> using namespace std;  struct list{     int data;     list *next; };  list * create(){     char a;     int i=1;     list *move,*start,*temp;     start=new list();     temp=start;     cout<<"do u want enter new node. press y anything.\n";     cin>>a;     while(a=='y'){         cout<<"enter data node "<<i<<endl;         cin>>start->data;        move=new list();        start->next=move;        start=start->next;        i++;        cout<<"do u want enter new node. press y anything.\n";        cin>>a;     }     start->next=null;     return temp; }  void display(list *ob){     int i=1;     while(ob->next!=null){     cout<<"\ndata node "<<i<<" :"<<ob->data;     ob=ob->next;     i++; } }  void add(list *temp){  while(temp->data!=2){     temp=temp->next; } int data; list *var=temp; list *node1=new list(); temp->next=node1; var=var->next; node1->next=var; cout<<"enter data new node who's data 2"; cin>>data; node1->data=data; cout<<"data inserted";  }  int main(){      list *point=create();     add(point);     display(point); } 

if can me debug great help. thankyou. running infinite loop in display method. if run program without method add runs fine.

here's simple modification make code work, in add(list*)

int data; list *node1 = new list; node1->next = temp->next; temp->next = node1; 

we set next of node1 after creating it, set the value temp->next node1.


Comments