队列的链式实现

来源:互联网 发布:linux里sort怎么用 编辑:程序博客网 时间:2024/05/16 17:48
/*2015年9月29日18  杨毅Oneal 
队列的链式实现及其简单操作*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef char DataType;


struct LQNode/*链队结点*/
{
DataType data;/*数据域*/
struct LQNode *next;/*指针域*/
};


struct LQueue/*链队*/
{
struct LQNode *front;/*头结点指针*/
struct LQNode *rear;/*尾结点指针*/
};


struct LQueue *InitLQueue(void)/*创建一个带空节点的空队列*/
{
struct LQueue *Q;
struct LQNode *p;
if(!(Q=(struct LQueue *)malloc(sizeof(struct LQueue))))
exit(-1);
    if(!(p=(struct LQNode *)malloc(sizeof(struct LQNode))))
exit(-2);/*动态分配空间,若分配失败则以负数退出*/
p->next=NULL;/*队为空*/
Q->front=Q->rear=p;/*队首、队尾指针相同*/
return Q;/*返回创建的队列*/
}


int InQueue(struct LQueue *Q,DataType x)/*插入元素x*/
{
struct LQNode *p;
if(!(p=(struct LQNode *)malloc(sizeof(struct LQNode))))
exit(-2);
p->data=x;
p->next=NULL;
Q->rear->next=p;/*将新节点插入链队队尾*/
Q->rear=p;/*调整队尾指针*/
return 1;
}
int OutQueue(struct LQueue *Q,DataType *x)/*删除队列的第一个结点,并以x带回其值*/
{
struct LQNode *p;
if(Q->front==Q->rear)
{
printf("队列为空,不能出队!\n");
exit(1);
}
p=Q->front->next;/*对于链式存储的,在进行删除后,都应释放其空间,将权限还给系统。否则内存会越用越少。*/
*x=p->data;/*将队首值放入x*/
Q->front->next=p->next;/*修改队首指针*/
free(p);
return 1;
}
int EmptyQueue(struct LQueue *Q)/*判断队列是否为空*/
{
if(Q->front==Q->rear)
return 1;
else
return 0;
}


int PrintQueue(struct LQueue *Q)/*打印队列*/
{
struct LQNode *p;
p=Q->front->next;/*跳过无值的头结点*/
if(p==NULL)
printf("该队列为空");
else
while(p->next!=NULL)
{
printf("%c->",p->data);
p=p->next;
}
printf("NULL\n");
return 0;
}
int main(void)
{
struct LQueue *Q;
DataType x;
int temp=1;/*为了测试每次操作后的返回值*/
/*测试*/
Q=InitLQueue();
if(temp==EmptyQueue(Q))
printf("成功创建带空结点空队列!\n");
InQueue(Q,'a');
InQueue(Q,'b');
InQueue(Q,'c');
InQueue(Q,'d');
InQueue(Q,'\0');


printf("初始化后,队列为:\n");
PrintQueue(Q);


OutQueue(Q,&x);
printf("删除第一个结点%c\n",x);
OutQueue(Q,&x);
printf("删除第二个结点%c\n",x);


printf("进行删除后队列为:\n");
PrintQueue(Q);


if(temp==EmptyQueue(Q))
printf("队列非空\n");


return 0;
}
0 0