用两个栈(后进先出)实现队列(先进先出)
typedef int STDataType;
typedef struct Stack
{
STDataType* _a;//数组
int _top; // 栈顶,类似顺序表中的_size
int _capacity; // 容量
}Stack;
// 初始化栈
void StackInit(Stack* ps)
{
assert(ps);
ps->_a = NULL;
ps->_capacity = 0;
ps->_top = 0;
}
// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0
bool StackEmpty(Stack* ps)
{
assert(ps);
return ps->_top == 0;
}
// 入栈
void StackPush(Stack* ps, STDataType data)
{
assert(ps);
//扩容
if (ps->_capacity == ps->_top)
{
int newcapacity = ps->_capacity == 0 ? 4 : 2 * (ps->_capacity);
STDataType* tmp = (STDataType*)realloc(ps->_a, newcapacity * sizeof(STDataType));
if (tmp == NULL)
{
perror("realloc fail");
return;
}
ps->_a = tmp;
ps->_capacity = newcapacity;
}
ps->_a[ps->_top++] = data;
}
// 出栈
void StackPop(Stack* ps)
{
assert(ps);
assert(!StackEmpty(ps));
ps->_top--;
}
// 获取栈顶元素
STDataType StackTop(Stack* ps)
{
assert(ps);
return ps->_a[ps->_top-1];
}
// 获取栈中有效元素个数
int StackSize(Stack* ps)
{
assert(ps);
return ps->_top;
}
// 销毁栈
void StackDestroy(Stack* ps)
{
assert(ps);
ps->_capacity = ps->_top = 0;
free(ps->_a);
ps->_a = NULL;
}
typedef struct {
Stack Spush;
Stack Spop;
} MyQueue;
MyQueue* myQueueCreate() {
MyQueue*p=(MyQueue*)malloc(sizeof(MyQueue));
StackInit(&p->Spush);
StackInit(&p->Spop);
return p;
}
void myQueuePush(MyQueue* obj, int x) {
StackPush(&obj->Spush,x);
}
int myQueuePeek(MyQueue* obj) {
if(StackEmpty(&obj->Spop))
{
while(!StackEmpty(&obj->Spush))
{
int top=StackTop(&obj->Spush);
StackPush(&obj->Spop,top);
StackPop(&obj->Spush);
}
}
return StackTop(&obj->Spop);
}
int myQueuePop(MyQueue* obj) {
int front=myQueuePeek(obj);
StackPop(&obj->Spop);
return front;
}
bool myQueueEmpty(MyQueue* obj) {
return StackEmpty(&obj->Spop)&&StackEmpty(&obj->Spush);
}
void myQueueFree(MyQueue* obj) {
StackDestroy(&obj->Spop);
StackDestroy(&obj->Spush);
free(obj);
}
/**
* Your MyQueue struct will be instantiated and called as such:
* MyQueue* obj = myQueueCreate();
* myQueuePush(obj, x);
* int param_2 = myQueuePop(obj);
* int param_3 = myQueuePeek(obj);
* bool param_4 = myQueueEmpty(obj);
* myQueueFree(obj);
*/