用栈实现队列
要想用栈实现队列功能,则至少需要2个栈。
存储数据的栈按照栈的后进先出原则依次进入另一个栈,再按照栈的后进先出原则出栈就实现了队列的先进先出,相当于负负得正的感觉。
typedef int type;
typedef struct Stack {
type* array;
size_t size;
size_t capacity;
}Stack;
//栈初始化
void StackInit(Stack* sl, size_t n) {
sl->array = (type*)malloc(sizeof(type) * n);
sl->capacity = n;
sl->size = 0;
}
//入栈
void StackPush(Stack* sl, type x) {
if (sl->size == sl->capacity) {
sl->capacity *= 2;
sl->array = (type*)realloc(sl->array, sl->capacity);
//扩容
}