链式队列的简单案例实现:
#include <stdio.h>
#include <iostream>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define OVERFLOW -1
typedef int Status;
typedef int QElemType;
//队列的链式存储结构
typedef struct QNode
{
QElemType data;
struct QNode *next;
} QNode, *QueuePtr;
typedef struct
{
QueuePtr front;
QueuePtr rear;
} LinkQueue;
//初始化
//构造一个空队列,头指针和尾指针都指向头结点
Status InitQueue(LinkQueue &Q)
{
Q.front = Q.rear = new QNode;
Q.front->next = NULL;
return OK;
}
//入队
Status EnQueue(LinkQueue &Q, QElemType e)
{
QNode *p = new QNode;
p->data = e;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
return OK;
}
//出队
Status DeQueue(LinkQueue &Q, QElemType &e)
{
if (Q.front == Q.rear)
{
puts("出队失败..");
return ERROR;
}
QNode *p = Q.front->next; // 指向首元结点 方便操作和后续释放
e = p->data;
Q.front->next = p->next;
if (Q.rear == p->next)
Q.front = Q.rear; // 将最后一个结点出栈,则为设置为空
delete p;
return OK;
}
//取队头元素
QElemType GetHead(LinkQueue Q)
{
if (Q.front == Q.rear)
{
puts("取队头元素失败...");
return ERROR;
}
return Q.front->next->data;
}
int main(void)
{
LinkQueue Q;
puts("初始化链队...");
InitQueue(Q);
puts("将data为1 2 3的结点入队...");
EnQueue(Q, 1);
EnQueue(Q, 2);
EnQueue(Q, 3);
puts("入队成功..");
puts("取队头元素...");
printf("e: %d\n", GetHead(Q));
puts("出队ing...");
int e;
DeQueue(Q, e);
printf("出队的元素e: %d\n", e);
puts("取队头元素...");
printf("e: %d\n", GetHead(Q));
delete Q.front;
return 0;
}