c++ - 我总是在运行这个程序时遇到无限循环。

标签 c++ linked-list

此代码用于在列表中找到“2”的值/数据后在链表中插入节点。

#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);
}

如果有人能帮我调试它,那将是一个很大的帮助。谢谢。 我在显示方法中遇到了无限循环。如果我在没有添加方法的情况下运行该程序,那么它运行良好。

最佳答案

这是一个简单的修改,可以使您的代码在 add(list*)

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

我们在创建 node1 后立即设置 next ,然后我们只需将值 temp->next 设置为 node1.

关于c++ - 我总是在运行这个程序时遇到无限循环。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31424861/

相关文章:

递归调用函数以在 C 中创建列表

c++ - 神奇分配的链表中的头指针,不应该工作但确实如此

c++ - 升序排序 - 链表

c++ - 将句子作为用户的字符串输入读取

c++ - 如何在 Linux 中安装仅 header (odeint) 库?

c++ - 指针引用类型的序列

java - LinkedList 在 Java 内部是如何工作的?

c++ - LinkedStack 及其模板类

c++ - 输入字母 f 或任何字母并计算字母表模式,如 abc abcd abcde abcdef 但它仅在我按 0 时有效

c - 将链表数组传递给函数