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

流过昼夜 提交于 2020-01-17 05:39:04

问题


This code is for the insertion of a node in a linked list after a value/data of "2" is found in the 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 to enter a new node. Press y but anything.\n";
    cin>>a;
    while(a=='y'){
        cout<<"Enter data for node "<<i<<endl;
        cin>>start->data;
       move=new list();
       start->next=move;
       start=start->next;
       i++;
       cout<<"Do u want to enter a new node. Press y but anything.\n";
       cin>>a;
    }
    start->next=NULL;
    return temp;
}

void display(list *ob){
    int i=1;
    while(ob->next!=NULL){
    cout<<"\nData for node "<<i<<" is :"<<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 for new node who's data is 2";
cin>>data;
node1->data=data;
cout<<"data inserted";

}

int main(){

    list *point=create();
    add(point);
    display(point);
}

If anyone can help me debug it then it would be a great help. Thankyou. I am running into infinite loop in the display method. If I run the program without the method add then it runs fine.


回答1:


Here's a simple modification that would make your code work, in add(list*)

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

we set the next of node1 immediately after creating it, then we just set the the value temp->next to node1.




回答2:


After executing of

add(point)

point variable will point to list elem with data field equale to 2.
And here

list *var=temp;
list *node1=new list();
temp->next=node1;
var=var->next;
node1->next=var;

you create infinity loop.
Assume at first temp and var point to elem1 and node1 to new elemN.

temp->next = node1; // elem1.next ---> elemN
var = var->next; // var(elem1) ---> elemN
node1->next = var; // elemN.next ---> elemN

One of possible implementation of add

void add(list *temp){
    list *var=temp;
    while(var->data!=2){
        var=var->next;
    }
    int data;
    list *node1=new list();
    list *nextelem = var->next;
    var->next=node1;
    node1->next=nextelem;
    cout<<"Enter data for new node who's data is 2";
    cin>>data;
    node1->data=data;
    cout<<"data inserted";
}


来源:https://stackoverflow.com/questions/31424861/i-always-run-into-a-infinite-loop-on-running-this-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!