#include<iostream>
using namespace std;
typedef int ElemType;
typedef struct Node
{
ElemType data;
struct Node *pNext;
}Node, *pNode;
typedef struct {
pNode pFront;
pNode pRear;
}Queue;
void InitQueue(Queue &Q)//队中的两个针指向一个不存放有效元素的头节点
{
Q.pFront = new Node;
Q.pRear = Q.pFront;
Q.pFront->pNext = NULL;
}
void DestroyQueue(Queue &Q)
{
while (Q.pFront)
{
Q.pRear = Q.pFront->pNext;
delete Q.pFront;
Q.pFront = Q.pRear;
}
}
bool QueueEmpty(Queue Q)
{
if (Q.pRear == Q.pFront)
return true;
else
return false;
}
void EnQueue(Queue &Q, ElemType e)
{
pNode pNew = new Node;
pNew->data = e;
pNew->pNext = NULL;
Q.pRear->pNext = pNew;
Q.pRear = pNew;
pNew = NULL;
}
bool DeQueue(Queue &Q, ElemType &e)
{
if (QueueEmpty(Q))
return false;
pNode pTem = Q.pFront->pNext;
e = pTem->data;
Q.pFront->pNext = pTem->pNext;
if (Q.pRear == pTem)//当队中只有一个有效元素时
Q.pRear = Q.pFront;
delete pTem;
pTem = NULL;
return true;
}
bool GetHead(Queue Q, ElemType &e)
{
if (QueueEmpty(Q))
return false;
e = Q.pFront->pNext->data;
return true;
}
void VisitElem(ElemType e)
{
cout << e << " ";
}
void DisPlay(Queue Q)
{
if (QueueEmpty(Q))
{
cout << "Indeed Empty! No Print!" << endl;
return;
}
pNode pTem = Q.pFront->pNext;
while (pTem)
{
VisitElem(pTem->data);
pTem = pTem->pNext;
}
cout << endl;
}
int main(void)
{
Queue Q;
ElemType e = 0;
InitQueue(Q);
EnQueue(Q, 1);
EnQueue(Q, 2);
EnQueue(Q, 3);
EnQueue(Q, 4);
EnQueue(Q, 5);
EnQueue(Q, 6);
if (GetHead(Q, e))
VisitElem(e);
cout << endl;
DisPlay(Q);
DeQueue(Q, e);
DeQueue(Q, e);
DisPlay(Q);
return(0);
}
数据结构之链队
最新推荐文章于 2022-05-16 19:52:30 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)