#include<iostream>
#define MAZSIZE 100
#define OK 1
#define ERROR 0
using namespace std;
typedef int QElemType;
//------------定义节点结构-------------
typedef struct QNode
{
QElemType data;
struct QNode *next;
}QNode, *QueuePtr;
//-------定义队列头尾指针结构----------
typedef struct{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
//------------建单链队列---------------
int InitQueue(LinkQueue &Q)
{
//分配一个节点,即头结点,头指针和尾指针均指向此头结点
Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
if (!Q.front) return ERROR;
Q.front->next = NULL;
return OK;
}
//------------向队尾中插入数据----------
void EnQueue(LinkQueue &Q,QElemType e)
{
QNode *p;
p = (QueuePtr)malloc(sizeof(QNode));
if (!p)
{
cout << "OVERFLOW!" << endl;
}
p->data = e;
p->next =Q.rear->next; //单链队列的为节点的next为NULL
Q.rear->next = p;
Q.rear = p;
}
//-------------删除队头元素-------------
void DeQueue(LinkQueue &Q)
{
QNode *p;
if (Q.front == Q.rear)
{
cout << "单链队列为空!" << endl;
}
else
{
if (Q.front->next == Q.rear)
{
p = Q.front->next;
Q.front->next = p->next;
Q.rear = Q.front;
}
else
{
p = Q.front->next;
Q.front->next = p->next;
free(p);
}
}
}
//-------------打印单链队列--------------
void PrintQuede(LinkQueue &Q)
{
QNode *p;
p = Q.front;
cout << "单链队列的元素:" << endl;
if (Q.front == Q.rear)
{
cout << "单链队列为空!" << endl;
}
else
{
while (p != Q.rear)
{
p = p->next;
cout << p->data << endl;
}
}
}
//-----------销毁队列-------------
void DestroyQueue(LinkQueue &Q)
{
while (Q.front)
{
Q.rear = Q.front->next;
Q.front = Q.rear;
}
cout << "队列销毁成功!" << endl;
}
//--------------main()------------
void main()
{
LinkQueue Q;
QElemType e1, e2, e3, e4;
e1 = 1;
e2 = 2;
e3 = 3;
e4 = 4;
cout << endl << endl << "单链队列的实现以及相关操作";
cout << endl << "==========================" << endl;
InitQueue(Q); //建单链队列
EnQueue(Q, e1); //插入节点元素
EnQueue(Q, e2);
EnQueue(Q, e3);
EnQueue(Q, e4);
PrintQuede(Q); //打印单链队列
DeQueue(Q); //删除队头
PrintQuede(Q);
DestroyQueue(Q); //销毁单链队列
system("pause"); //防止结果一闪而过
}
单链队列的建立,插入,删除,打印,销毁
最新推荐文章于 2021-08-27 17:03:13 发布