我总是遇到一个无限循环运行这个程序。
问题描述:
此代码用于在列表中找到值/数据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
.