/************************************************************************/
/* 队列的链式实现 */
/************************************************************************/
#include <stdio.h>
#include <STDLIB.H>
#define _ERROR 0
#define _OK 1
typedef int QElementType;
typedef int status;
typedef struct QNode
{
QElementType data;
struct QNode *next;//下一个节点
} QNode,*QueuePtr;
/*队列的数据抽象*/
typedef struct
{
QueuePtr front;//队首指针(出队)[指向准出队元素]
QueuePtr rear;//队尾指针(入队)[指向刚入队元素]
}LinkQueue;
/*队列的初始化*/
status InitQueue(LinkQueue &Q)
{
Q.front=NULL;
Q.rear=NULL;
return _OK;
}
/*判断队列是否为空*/
bool IsEmpty(LinkQueue Q)
{
return Q.front==NULL;
}
/*入队*/
status InQueue(LinkQueue &Q,QElementType e)
{
//构造节点
QNode *ptrNode =(QNode*) malloc(sizeof(QNode));
if(!ptrNode)
return _ERROR;
ptrNode->data=e;
ptrNode->next=NULL;
if(IsEmpty(Q))//判断队列是否为空
{Q.front=Q.rear=ptrNode;
return _OK;}
//如果不为空
Q.rear->next=ptrNode;
Q.rear = ptrNode;
return _OK;
}
/*出队*/
status OutQueue(LinkQueue &Q,QElementType &e)
{
if(IsEmpty(Q))
return _ERROR;
QNode *tempPtr = Q.front;
e=tempPtr->data;
Q.front = tempPtr->next;
free(tempPtr);
return _OK;
}
/*打印队列中的元素*/
void PrintQueue(LinkQueue Q)
{
QNode *tempPtr = Q.front;
while(tempPtr!=NULL)
{
printf("%d \n",tempPtr->data);
tempPtr=tempPtr->next;
}
}
void main()
{
LinkQueue Q;
//初始化
InitQueue(Q);
if(IsEmpty(Q))
printf("队列此时为空\n");
else
printf("队列此时不为空\n");
//入队列
printf("入队列\n...........\n");
InQueue(Q,1);
InQueue(Q,2);
InQueue(Q,3);
InQueue(Q,4);
//打印
printf("打印队列元素\n");
PrintQueue(Q);
QElementType e;
//出队列
printf("出队列\n............\n");
OutQueue(Q,e);
printf("出元素%d\n",e);
OutQueue(Q,e);
printf("出元素%d\n",e);
/*打印*/
printf("打印队列元素\n");
PrintQueue(Q);
/*越界测试*/
printf("越界测试\n..........\n");
OutQueue(Q,e);
OutQueue(Q,e);
OutQueue(Q,e);
OutQueue(Q,e);
printf("正常\n");
}
队列的链式实现
最新推荐文章于 2024-04-02 17:09:52 发布