【发布时间】:2020-04-09 05:48:42
【问题描述】:
这段代码有几个问题;
首先,如果我运行它,然后我选择 PUSH 并输入两个名字,例如“Emily Glassberg”,它会进入 infinite循环,但如果我只输入一个名字,比如“Michael”,它会很好用。Problem picture.
其次,当我运行代码后
- 选择“PUSH” - 输入一个名称-
- 然后选择“删除”
- 然后选择“PUSH” - 并再次输入一个名称 - 程序崩溃,
如果我仅在输入任何名称之前选择“删除”,它甚至会崩溃。
Problem 2.1 picture
Problem 2.2 picture
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
struct Queue
{
struct node
{
node *next;
string name;
};
node *head;
int front=-1,rare=-1;
void push(string x)
{
if (rare < 0 )
{
head =new node;
head->next=NULL;
head->name=x;
rare ++;
}
else
{
node *temp,*temp1;
temp=head;
while(temp->next != NULL){temp=temp->next;}
temp1=new node;
temp->next=temp1;
temp1->next=NULL;
temp1->name=x;
}
}
void display()
{
node *temp;
temp=head;
if (rare < 0)
{
cout <<"Queue under flow";
return;
}
cout<<"\nthe queue is: \n\n";
while(temp != NULL)
{
cout <<temp->name<<endl;
temp=temp->next;
}
}
void pop()
{
if( rare < 0)
{
cout <<"Queue under flow\n";
return;
}
if(front == rare)
{
front = rare =-1;
head=NULL;
return;
}
front++;
head=head->next;
}
Queue Delete(Queue q){
node* temp = head;
while (head != nullptr){
head = head->next;
delete temp;
temp = head;
}
head = nullptr;
}
};
main()
{
Queue q1;
string x;
int ch;
while(true)
{
cout<<"1.PUSH\n2.POP\n3.DISPLAY\n4.DELETE\n5.EXIT\nenter Ur choice:\n";
cin >> ch;
switch(ch)
{
case 1:
cout <<"plz,enter the name \n";
cin >> x;
q1.push(x);
cout<<"\n";
break;
case 2:
q1.pop();
break;
case 3:
q1.display();
cout<<"\n";
break;
case 4:
q1.Delete(q1);
break;
case 5:
exit(0);
default :
cout<<"error selection.plz,try again\n";
}
}
return (0);
}
【问题讨论】:
-
调试时尝试制作一个示例,该示例一次暴露一个错误并且不需要输入。这使您能够以尽可能少的干扰进行调试。使用minimal reproducible example 作为灵感。
标签: c++ linked-list crash queue infinite-loop