一直编译不过去,分析问题后发现是5提前入了创建的第二个栈,但一直找不到原因,于是测试了一下,发现一个很矛盾的问题。
题目链接如下
https://leetcode.cn/problems/implement-queue-using-stacks/
测试结果如下
代码如下
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top;
int capacity;
}ST;
void STInit(ST* ps);
void STDestroy(ST* ps);
//入栈
void STPush(ST* ps,STDataType x);
//出栈
void STPop(ST* ps);
int STSize(ST* ps);
bool STEmpty(ST* ps);
//获取栈顶元素
STDataType STTop(ST* ps);
void STInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->capacity = 0;
ps->top = 0;
}
void STDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = ps->capacity = 0;
}
void STPush(ST* ps, STDataType x)
{
assert(ps);
// 11:40
if (ps->top == ps->capacity)
{
int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDataType* tmp = (STDataType*)realloc(ps->a, sizeof(STDataType) * newCapacity);
if (tmp == NULL)
{
perror("realloc fail");
exit(-1);
}
ps->a = tmp;
ps->capacity = newCapacity;
}
ps->a[ps->top] = x;
ps->top++;
}
void STPop(ST* ps)
{
assert(ps);
//
assert(ps->top > 0);
--ps->top;
}
STDataType STTop(ST* ps)
{
assert(ps);
//
assert(ps->top > 0);
return ps->a[ps->top - 1];
}
int STSize(ST* ps)
{
assert(ps);
return ps->top;
}
bool STEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
typedef struct {
ST st1;
ST st2;
} MyQueue;
MyQueue* myQueueCreate() {
MyQueue* myque =(MyQueue*)malloc(sizeof(MyQueue));
STInit(&myque->st1);
STInit(&myque->st2);
return myque;
}
void myQueuePush(MyQueue* obj, int x) {
STPush(&obj->st1,x);
}
int myQueuePeek(MyQueue* obj) {
if(STEmpty(&obj->st2)==true);
{
//导数据
while(!STEmpty(&obj->st1))
{
STPush(&obj->st2,STTop(&obj->st1));
STPop(&obj->st1);
}
}
return STTop(&obj->st2);
}
int myQueuePop(MyQueue* obj) {
int front =myQueuePeek(obj);
STPop(&obj->st2);
return front;
}
bool myQueueEmpty(MyQueue* obj) {
return STEmpty(&obj->st1)&&STEmpty(&obj->st2);
}
void myQueueFree(MyQueue* obj) {
STDestroy(&obj->st1);
STDestroy(&obj->st2);
free(obj);
}