数据结构 队列的基本操作
【摘要】 #include <stdio.h>#include <stdlib.h> #define OK 1#define ERROR 0#define OVERFLOW -2 typedef int QElemType; typedef struct QNode{ QElemType data; struct QNode *next;}QNode, *Q...
-
#include <stdio.h>
-
#include <stdlib.h>
-
-
#define OK 1
-
#define ERROR 0
-
#define OVERFLOW -2
-
-
typedef int QElemType;
-
-
typedef struct QNode
-
{
-
QElemType data;
-
struct QNode *next;
-
}QNode, *QueuePtr;
-
-
typedef struct
-
{
-
QueuePtr front; /*Q.front相当于单链表的头结点,即Q.front->next是第一个数据*/
-
QueuePtr rear; /*Q.rear指向最后一个数据,,即Q.rear->next = NULL*/
-
}LinkQueue;
-
-
int InitQueue(LinkQueue &Q)
-
{
-
Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
-
if (!Q.front)
-
{
-
exit(OVERFLOW);
-
}
-
Q.front ->next = NULL;
-
return OK;
-
}
-
-
int EnQueue(LinkQueue &Q, QElemType e)
-
{
-
QueuePtr p;
-
p = (QueuePtr)malloc(sizeof(QNode));
-
if (!p)
-
{
-
exit(OVERFLOW);
-
}
-
p->data = e;
-
p->next = NULL;
-
Q.rear ->next = p;/*插入第一个节点时,也是Q.front->next = p;*/
-
Q.rear = p;/*队尾始终指向最后一个元素,即Q.rear->next = NULL*/
-
return OK;
-
}
-
-
-
int DeQueue(LinkQueue &Q, QElemType &e)
-
{
-
QueuePtr p;
-
if (Q.front == Q.rear)
-
{
-
return ERROR;
-
}
-
p = Q.front->next;
-
e = p->data;
-
Q.front->next = p->next;
-
if (Q.rear == p )
-
{
-
Q.rear = Q.front ;
-
}
-
free(p);
-
return OK;
-
}
-
-
int DestroyQueue(LinkQueue &Q)
-
{
-
while (Q.front)
-
{
-
Q.rear = Q.front->next ;
-
free(Q.front);
-
Q.front = Q.rear;
-
}
-
return OK;
-
}
-
-
int isQueue_Empty(LinkQueue Q)
-
{
-
if (Q.front == Q.rear)
-
{
-
return 1;
-
}
-
return 0;
-
}
-
-
void Print_Queue(LinkQueue Q)
-
{
-
if (isQueue_Empty(Q))
-
{
-
return;
-
}
-
while (Q.front != Q.rear)
-
{
-
printf("%d ",Q.front->next->data);
-
Q.front = Q.front->next;
-
}
-
printf("\n");
-
}
-
-
int main()
-
{
-
int i,n,e;
-
LinkQueue Q;
-
scanf("%d",&n);
-
InitQueue(Q);
-
for (i=0; i<n; i++)
-
{
-
scanf("%d",&e);
-
EnQueue(Q, e);
-
}
-
Print_Queue(Q);
-
DeQueue(Q,e);
-
Print_Queue(Q);
-
EnQueue(Q, 100);
-
Print_Queue(Q);
-
EnQueue(Q, 200);
-
Print_Queue(Q);
-
DestroyQueue(Q);
-
return 0;
-
}
文章来源: blog.csdn.net,作者:悦来客栈的老板,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/qq523176585/article/details/17249143
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)