#include <stdio.h>
#include <stdlib.h>
#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;
}
C语言:使用两个栈模拟一个队列
最新推荐文章于 2024-08-23 13:17:38 发布