c++实现队列基本操作,进队,出队,遍历队列
2019-11-26
#include <iostream>
using namespace std;
typedef int DataType;
#define Node ElemType
class Node
{
public:
DataType data;
ElemType *next;
};
class QueueLinkList
{
public:
QueueLinkList();
~QueueLinkList();
int IsEmpty();
void Enqueue(DataType data);
void Dequeue();
void PrintfQueue();
private:
ElemType *front;
ElemType *rear;
};
QueueLinkList::QueueLinkList()
{
front = new ElemType;
front->data = 0;
front->next = NULL;
rear = front;
}
QueueLinkList::~QueueLinkList()
{
delete front;
}
判断队列是否为空
int QueueLinkList::IsEmpty()
{
return front->next == NULL;
}
void QueueLinkList::Enqueue(DataType data)
{
ElemType *newNode = new ElemType;
newNode->data = data;
newNode->next = NULL;
rear->next = newNode;
rear = newNode;
}
void QueueLinkList::Dequeue()
{
if (front->next == NULL)
{
cout << "队为空" << endl;
return;
}
ElemType *ptemp = front->next;
front->next = ptemp->next;
delete ptemp;
}
void QueueLinkList::PrintfQueue()
{
ElemType *p = front;
if (front->next == NULL)
{
cout << "队为空" << endl;
return;
}
while (p->next != NULL)
{
p = p->next;
cout << p->data << " ";
}
cout << endl;
}
int main()
{
QueueLinkList q;
int i;
cout << "1.判断队是否为空 2.入队 3.出队 4.打印队 0.退出" << endl;
do
{
cout << "请输入要执行的操作:";
cin >> i;
switch (i)
{
case 1:
if (q.IsEmpty() == 1)
cout << "空队" << endl;
else
{
cout << "不是空队" << endl;
}
break;
case 2:
int n;
cout << "请输入要入队的值:";
cin >> n;
q.Enqueue(n);
break;
case 3:
q.Dequeue();
break;
case 4:
cout << "打印队列" << endl;
q.PrintfQueue();
break;
default:
cout << "输入的操作值错误" << endl;
break;
}
} while (i != 0);
system("pause");
return 0;
}