//链队列
#include<iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
class linkque
{
Node *front, *rear;//队头指针,队尾指针
public:
linkque();
~linkque();
void enque(int x);//入队
int deque();//出队
int getque();//返回队头元素
bool empty();//判断是否为空
void output();//输出队列
};
linkque::linkque()
{
Node *s = new Node;
s->next = NULL;
front = rear = s;
}
linkque::~linkque()
{
Node *p = front;
while (p)
{
Node *q = p;
p = p->next;
delete q;
}
}
void linkque::enque(int x)//入队
{
Node *p = new Node;
p->data = x;
p->next = NULL;
rear->next = p;
rear = p;
}
int linkque::deque()//出队
{
if (rear == front)
{
cout << "下溢" << endl;
exit(1);
}
Node *p = front->next;
int x = p->data;
front->next = p->next;
if (p->next == NULL)
rear = front;
delete p;
return x;
}
int linkque::getque()//返回队头元素
{
if (rear==front)
{
cout << "下溢" << endl;
exit(1);
}
int x = front->next->data;
return x;
}
bool linkque::empty()//判断是否为空
{
return rear == front;
}
void linkque::output()//输出队列
{
Node *p = front->next;
while (p !=NULL)
{
int x = p->data;
cout << x << " ";
p = p->next;
}
cout << endl;
}
int main()
{
linkque a;
cout << "将元素5,1,3依次入队" << endl;
a.enque(5);
a.enque(1);
a.enque(3);
cout << "输出队列:";
a.output();
cout << "返回队头元素为:";
cout << a.getque() <<endl;
cout << "将队头元素出队 " ;
a.deque();
cout << "输出队列:";
a.output();
cout << "判断是否为空?" << endl;
if (!a.empty())
cout << "队列非空" << endl;
else
cout << "队列为空" << endl;
system("pause");
return 0;
}
输出结果: