顺序队的C语言实现

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_44833327/article/details/102684422

本队实现和取队首入队出队的操作

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define ok 1
#define error 0
#define true 1
#define maxn 100
#define num 10
typedef struct {
int *head;
int *tail;
int size;
}queue;
int initqueue(queue *s)
{
s->tail =(int *)malloc(maxn*sizeof(int));
if(!s->tail)
{
return error;
}
s->head=s->tail;
s->size=maxn;
return ok;
}
//进队 
int push(queue *s,int *e)
{
if(s->head-s->tail>=s->size)
{
s->tail=(int *)realloc(s->tail,(s->size+num)*sizeof(int));

}
if(!s->tail)
{return error;
}
*s->head++=*e;
return ok;
}

//出队 
int pop(queue *s)
{
if(s->head==s->tail)

return error;

return *--s->head;
}
//取队首 
int tail(queue *s)
{
int e;
if(s->head==s->tail)
return error;
e=*(s->head-1);
printf("队顶元素为%d\n",e);
return 0;
}
//遍历输出 
void showqueue(queue *s)
{
int *p=s->head;
while(true)
{
printf("%d ",*--p);
if(s->tail==p)
{
break;
}
}
printf("\n");
}
int main()
{
queue s;
int i,x,n;
printf("创建个线性的队\n\n"); 
initqueue(&s); 
printf("请输入n个数将其压入队\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&x);
push(&s,&x);
}
tail(&s);
printf("从队首开始显示队中的元素"); 
showqueue(&s);
printf("弹出队中的三个元素");
for(i=0;i<3;i++)
{
pop(&s);
}
printf("更新后的队中元素");
showqueue(&s);
return 0;
}



猜你喜欢

转载自blog.csdn.net/qq_44833327/article/details/102684422