//ADT LinkQueue
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define OVERFLOW -1
typedef int QElemType;
typedef int Status;
typedef struct QNode {
QElemType data;
struct QNode *next;
}QNode, *QueuePtr;
typedef struct {
QueuePtr front;//头指针
QueuePtr reer;//尾指针
}LinkQueue;
//构造一个空队列
Status InitQueue(LinkQueue &Q) {
Q.front = Q.reer = (QNode *)malloc(sizeof(QNode));
if(!Q.front) exit(OVERFLOW);
Q.front->next = NULL;
return OK;
}
//销毁队列Q
Status DestroyQueue(LinkQueue &Q) {
QueuePtr p = Q.front, postp;
while(p) {
postp = p->next;
free(p);
p = postp;
}
Q.front = Q.reer = NULL;
return OK;
}
//清空队列
Status ClearQueue(LinkQueue &Q) {
Q.reer = Q.front;
Q.front->next = NULL;
return OK;
}
//插入元素
Status EnQueue(LinkQueue&Q, QElemType e) {
QueuePtr p = (QNode *)malloc(sizeof(QNode));
if(!p) exit(OVERFLOW);
p->data = e;
p->next = NULL;
Q.reer->next = p;
Q.reer = p;
return OK;
}
//删除元素
Status DeQueue(LinkQueue &Q,QElemType &e) {
if(Q.front == Q.reer) return ERROR;
QueuePtr p = Q.front->next;
e = p->data;
Q.front->next = p->next;
if(Q.reer == p) {
Q.reer = Q.front;
}
free(p);
return OK;
}
//判断队列是否为空
Status QueueEmpty(LinkQueue Q) {
if(Q.front == Q.reer) return TRUE;
return FALSE;
}
//求队列长度
int QueueLength(LinkQueue Q) {
int cnt = 0;
QueuePtr p = Q.front->next;
while(p) {
cnt++;
p = p->next;
}
return cnt;
}
//求队头元素的值
Status GetHead(LinkQueue Q, QElemType &e) {
if(Q.front == Q.reer) return ERROR;
QueuePtr p = Q.front->next;
e = p->data;
free(p);
return OK;
}
//遍历
Status QueueTraverse(LinkQueue Q) {
QueuePtr p = Q.front->next;
while(p) {
if(p == Q.front->next)cout << p->data;
else cout << ' ' << p->data;
p = p->next;
}
cout << endl;
}
ADT - 链式队列(LinkQueue)
最新推荐文章于 2022-11-01 16:04:13 发布