#include <iostream>
using namespace std;
typedef int element_type;
struct celltype
{
element_type element;
struct celltype *next;
};
struct QUEUE
{
celltype *front;
celltype *rear;
};
void MakeNull(QUEUE *Q)
{
Q->front = new celltype;//建立表头结点
Q->front->next = NULL;
Q->rear = Q->front;//表头既是第一个结点也是最后一个结点
}/*MakeNull*/
bool Empty(QUEUE *Q)
{
if(Q->front == Q->rear)
return true;
else
return false;
}//Empty
void EnQueue(element_type x,QUEUE *Q)//将元素x插入队列Q的后端
{
Q->rear->next = new celltype;//在队列的后端增加一个新节点
Q->rear = Q->rear->next;//将新节点作为表尾
Q->rear->element = x;
Q->rear->next = NULL;
}/*EnQueue*/
void DeQueue(QUEUE *Q)//删除队列Q的第一个元素
{
celltype *tmp;
if( Empty(Q) )
cout << "Queue is empty!" << endl;
else
{
/*也可以
tmp = Q->front->next;
Q->front->next = tmp->next;
delete tmp;
*/
Q->front->next = Q->front->next->next;
if(Q->front->next == NULL)
Q->rear = Q->front;
}
}
element_type Front(QUEUE *Q)//返回队列的第一个元素
{
if(Q->front->next)
return (Q->front->next->element);
else
cout << "Queue is empty!" << endl;
}
int main()
{
QUEUE *Q;
int m,n;
MakeNull(Q);
EnQueue(1,Q);
EnQueue(2,Q);
m = Front(Q);
cout << m << endl;
DeQueue(Q);
n = Front(Q);
cout << n << endl;
return 0;
}
[数据结构] 队列的指针实现
最新推荐文章于 2024-09-19 09:04:57 发布