您的位置:首页 > 编程语言 > C语言/C++

C语言实现队列(纯C)

2014-09-05 14:37 363 查看
1. [代码][C/C++]代码

#include <stdio.h>
#include <stdlib.h>
#define ElemType int
#define Status int
#define OK 1
#define ERROR 0
typedef struct QNode{
ElemType data;
struct QNode *next;
}QNode;
typedef struct LinkQueue{
QNode *front;
QNode *rear;
}LinkQueue;
Status InitQueue(LinkQueue *q)
{
q->front=q->rear=(QNode *)malloc(sizeof(QNode));
if(!q->front)
return ERROR;
q->front->next=NULL;
return OK;
}
Status EnQueue(LinkQueue *q,ElemType e)
{
QNode *p=(QNode *)malloc(sizeof(QNode));
if(!p)
return ERROR;
p->data=e;
p->next=NULL;
q->rear->next=p;//入队操作,从队尾(rear)进入
q->rear=p;//相当于rear++,q->rear指向下一个位置
//符合入队操作的基本要求
return OK;
}
Status DeQueue(LinkQueue *q,ElemType *e)
{
QNode *p=(QNode *)malloc(sizeof(QNode));
if(!p)
return ERROR;

p=q->front->next;//q指向的是front指针的下一个位置
//亦即队首元素
*e=p->data;
q->front->next=p->next;//出队操作后,front++
if(q->rear==p)//判断是否全部出队
q->rear=q->front;//如果全部出队,则将队列置为空
return OK;
}
Status Display(LinkQueue *q)
{http://www.huiyi8.com/dongman/weimei/​
QNode *p;
p=q->front->next;
while (p)
{唯美动漫图片
printf("%d ",p->data);
p=p->next;
}
printf("\n");
return OK;
}

Status PrintfQueue(LinkQueue *Q)
{
QNode *p;

for(p=Q->front->next;p!=NULL;p=p->next)
{
printf("%d",p->data);
}
}
int main(void)
{
int i,n;
ElemType e,de;
LinkQueue *q=(LinkQueue *)malloc(sizeof(QNode));
if(!q)
return ERROR;
InitQueue(q);
printf("请输入入队元素的个数:\n");
scanf("%d",&n);
printf("请输入入队的元素:\n");
for(i=0;i<n;++i)
{
scanf("%d",&e);
EnQueue(q,e);
}
printf("队列中的元素为:\n");
Display(q);
printf("出队元素为:\n");
DeQueue(q,&de);
printf("%d",de);
printf("\n");
printf("出队后剩余的序列为:\n");
Display(q);
free(q);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: