我总是遇到一个无限循环运行这个程序。 [英] I always run into a infinite loop on running this program.

查看:253
本文介绍了我总是遇到一个无限循环运行这个程序。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码用于在列表中找到值/数据2之后,在链接列表中插入节点。

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.

推荐答案

这里有一个简单的修改,让你的代码工作, add(list *)

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;

我们设置 next $ c> node1 立即创建它,然后我们只是将值 temp->下一个设置为 node1

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

这篇关于我总是遇到一个无限循环运行这个程序。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆