[数据结构-严蔚敏版]P61ADT Queue的表示与实现(单链队列-队列的链式存储结构)
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[数据结构-严蔚敏版]P61ADT Queue的表示与实现(单链队列-队列的链式存储结构)相关的知识,希望对你有一定的参考价值。
代码如下:
#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct QNode
{
ElemType data;
QNode *next;
}QNode ,*QueuePtr;
typedef struct
{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
bool initQueue(LinkQueue &q)
{
q.front = q.rear = new QNode;
if (!q.front) return false;
q.front->next = nullptr;
return true;
}
bool destroy(LinkQueue &q)
{
while (q.front)
{
q.rear = q.front->next;
delete q.front;
q.front = q.rear;
}
q.front = q.rear = nullptr;
return true;
}
bool clearQueue(LinkQueue &q)
{
QNode *p = q.front->next;
QNode *s = nullptr;
while (p)
{
s = p;
p = p->next;
delete s;
}
q.rear = q.front;
return true;
}
bool queueEmpty(LinkQueue q)
{
if (q.front == q.rear) return true;
return false;
}
int queueLength(LinkQueue q)
{
int j = 0;
QNode *p = q.front->next;
while (p)
{
j++;
p = p->next;
}
return j;
}
bool getHead(LinkQueue q, ElemType &e)
{
if (q.front == q.rear) return false;
e = q.front->next->data;
return true;
}
bool enQueue(LinkQueue &q, ElemType e)
{
QNode *p = new QNode;
if (!p) return false;
p->data = e;
p->next = nullptr;
q.rear->next = p;
q.rear = p;
return true;
}
bool deQueue(LinkQueue &q, ElemType &e)
{
if (q.front == q.rear) return false;
QNode *p = q.front->next;
q.front->next = p->next;
if (q.rear == p)q.rear = q.front;
delete p;
return true;
}
void vis(ElemType e)
{
cout << e << " ";
}
void queueTraverse(LinkQueue q, void(*visit)(ElemType))
{
QNode *p = q.front->next;
while (p)
{
visit(p->data);
p = p->next;
}
}
int main() {
LinkQueue q;
initQueue(q);
int n;
int a;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a;
enQueue(q, a);
}
queueTraverse(q, vis);
cout << endl;
deQueue(q, a);
deQueue(q, a);
queueTraverse(q, vis);
cout << endl;
cout << queueLength(q) << endl;
return 0;
}
以上是关于[数据结构-严蔚敏版]P61ADT Queue的表示与实现(单链队列-队列的链式存储结构)的主要内容,如果未能解决你的问题,请参考以下文章