我只是编程的入门者,我要做一些功课。 基本上,它应该是链接列表队列,而不使用全局变量。
有时我的程序崩溃,有时不会崩溃。
我不知道我在做什么错。
非常感谢您的帮助。
我认为问题可能出在del和print函数中。
#include <iostream>
using namespace std;
void menu()
{
cout << "Choose one of options" << endl;
cout << "1. New queue" << endl;
cout << "2. Attach" << endl;
cout << "3. Delete" << endl;
cout << "4. Print" << endl;
cout << "5. End" << endl;
}
struct el_FIFO
{
int x;
struct el_FIFO *nast;
};
struct FIFO
{
struct el_FIFO *front;
struct el_FIFO *rear;
};
void attach(struct FIFO *k, int el)
{
struct el_FIFO *nowy = new el_FIFO;
nowy->x = el;
nowy->nast = NULL;
if (k->front == NULL)
{
k->front = nowy;
k->rear = nowy;
}
else
{
k->rear->nast = nowy;
k->rear = nowy;
}
}
void del(struct FIFO *k)
{
struct el_FIFO *temp;
if (k->front != NULL)
{
temp = k->front->nast;
delete k->front;
k->front = temp;
}
else
{
cout << "There is no element to delete";
}
}
void new_queue(struct FIFO *k)
{
if (k->front == NULL)
{
cout << "queue is already empty";
}
else
{
while (k->front != NULL)
{
del(k);
}
cout << "queue is empty";
}
}
void print(struct FIFO *k)
{
struct FIFO *temp_FIFO;
if (k->front)
{
cout << "queue: " << endl;
while (k->front)
{
if (temp_FIFO->front == NULL)
{
temp_FIFO->front = k->front;
temp_FIFO->rear = k->front;
}
else
{
temp_FIFO->rear->nast = k->front;
temp_FIFO->rear = k->front;
}
cout << k->front->x << endl;
del(k);
}
while (temp_FIFO->front)
{
if (k->front == NULL)
{
k->front = temp_FIFO->front;
k->rear = temp_FIFO->front;
}
else
{
k->rear->nast = temp_FIFO->front;
k->rear = temp_FIFO->front;
}
del(temp_FIFO);
}
}
else
{
cout << "queue is empty";
}
}
int rear()
{
cout << "The end";
return 0;
}
int main()
{
struct FIFO *queue = new FIFO;
queue->front = NULL;
queue->rear = NULL;
int el = 0;
int c = 0;
do
{
menu();
cin >> c;
cout << endl;
switch (c)
{
case 1:
new_queue(queue);
cout << endl << endl;
break;
case 2:
cout << "Add element" << endl;
cin >> el;
attach(queue, el);
cout << endl;
break;
case 3:
cout << "Element will be deleted" << endl;
del(queue);
cout << endl << endl;
break;
case 4:
print(queue);
cout << endl;
break;
case 5:
rear();
break;
default:
cout << "You chose wrong" << endl << endl;
break;
}
} while (c != 5);
return 0;
}