c语言建多个栈,C语言:使用两个栈模拟一个队列

#include

#include

#define STACK_INIT_SIZE 100 //存储空间初始分配量

#define STACKINCREMENT //存储空间分配增量

typedef struct

{

int *base; //栈底

int *top; //栈顶

int stacksize;

} stack;

//构造一个空栈

int initStack(stack *s)

{

s->base = (int*)malloc(sizeof(int)*STACK_INIT_SIZE);

if(s->base == NULL)

{

printf("Memory allocate failed!\n");

return -1;

}

s->top = s->base;

s->stacksize = STACK_INIT_SIZE;

return 1;

}

//压栈的方法,i为需要压入栈顶的元素

int push(stack *s, int i)

{

//判断栈容量是否已经满了,如果已满,重新分配存储空间

if(s->top - s->base >= s->stacksize)

{

s->base = (int*)realloc(s->base, (s->stacksize+STACK_INIT_SIZE)*sizeof(int));

}

if(s->base == NULL)

{

printf("Memory allocate failed!\n");

return -1;

}

*s->top++ = i; //把元素压入

return 1;

}

//弹栈的方法

int pop(stack *s)

{

if(s->base == s->top)

return -1;

return *--s->top;

}

int main()

{

int i;

stack st1, st2;

initStack(&st1);

initStack(&st2);

//假设传入的队列为1,2,3,4,5,6

//则出栈的队列顺序为1,2,3,4,5,6

printf("Enter list is :\n");

for(i = 0; i < 7; i++)

{

push(&st1, i);

printf("%d ", i);

}

printf("\n");

//出栈的时候每次先把1栈中除栈顶元素之外的所有元素弹到2栈中

//然后在弹出1栈栈底元素

//最后再把2栈中的元素压入1栈中

//重复以上动作,直到1栈为空

printf("Exit the list is: ");

while(st1.base != st1.top)

{

while((st1.top - st1.base) > 1)

{

push(&st2, pop(&st1));

}

printf("%d ", pop(&st1));

while((st2.top - st2.base) > 0)

{

push(&st1, pop(&st2));

}

}

printf("\n");

return 0;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值