#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
typedef struct _seqstack
{
int data[MAXSIZE];
int top;
}seqstack;
int Initstack(seqstack *s)//置空栈
{
s->top = -1;
return 0;
}
int Display(seqstack *s)//显示队列
{
int n = 0;
if(s->top == -1)
{
printf("队为空");
}
else
{
while(s->top >= n)
{
printf("%d ",s->data[n]);
n++;
}
}
return 0;
}
int inqueue(int num,seqstack *s1,seqstack *s2)//进队列
{
if(s1->top == MAXSIZE - 1)//s1为满栈
{
printf("full\n");
}
else
{
if(s2->top != -1)//s1不是满栈且s2不是空栈
{
while(s2->top > -1)
{
s1->data[++s1->top] = s2->data[s2->top--];
}
s1->data[++s1->top] = num;
}
else//s1不是满栈且s2是空栈
{
s1->top++;
s1->data[s1->top] = num;
}
}
return 0;
}
int dequeue(seqstack *s1,seqstack *s2)//出队列
{
if(s2->top != -1)//s2不是空栈,直接弹出栈顶元素
{
printf("%d ",s2->data[s2->top--]);
}
else//如果s2空栈且s1不是空栈,把s1元素倒入s2中
{
if(s1->top != -1)
{
while (s1->top != -1)
{
s2->data[++s2->top] = s1->data[s1->top--];
printf("%d ",s2->data[s2->top--]);
}
}
else//如果s1和s2都是空栈
{
printf("empty\n");
}
}
return 0;
}
int main()
{
int i,j;
int select;
int choice = 1;
int num;
int account;
seqstack s1;
seqstack s2;
Initstack(&s1);//将两个栈置空
Initstack(&s2);
while(1)
{
printf("选择操作:1.in 2.out 3.exit \n");
scanf("%d",&select);
switch(select)
{
case 1:
{
printf("输入元素个数:");
scanf("%d",&account);
printf("输入数字:");
for(i = 0;i < account;i++)
{
scanf("%d",&num);
inqueue(num,&s1,&s2);
}
printf("队列中数据如下:");
Display(&s1);
printf("\n");
break;
}
case 2:
{
printf("出队的元素:");
dequeue(&s1,&s2);
printf("\n");
break;
}
case 3:
exit(0);
break;
}
}
return 0;
}
用两个栈实现一个队列
最新推荐文章于 2024-04-22 23:20:09 发布