文章目录
用栈模拟队列
pop函数中while循环对in或out的判断不带等号
while(in>0)
{
obj->outstack[out++] = obj->instack[--in];//不是in--,栈顶指向有数值的上一块
}
}
int re = obj->outstack[--out];
//回到输入栈
while(out>0)
{
obj->instack[in++] = obj->outstack[--out];
}
typedef struct {
int in,out;//两栈的栈顶
int instack[1001];
int outstack[1001];
} MyQueue;
MyQueue* myQueueCreate() {
MyQueue* queue = (MyQueue*)malloc(sizeof(MyQueue));
queue->in = 0;
queue->out = 0;
return queue;
}
void myQueuePush(MyQueue* obj, int x) {
obj->instack[(obj->in)++] = x;
}
int myQueuePop(MyQueue* obj) {
int out = obj->out;
int in = obj->in;
if(out==0)
{
while(in>0)
{
obj->outstack[out++] = obj->instack[--in];
}
}
int re = obj->outstack[--out];
//回到输入栈
while(out>0)
{
obj->instack[in++] = obj->outstack[--out];
}
obj->in = in;
obj->out = out;
return re;
}
//返回栈底元素
int myQueuePeek(MyQueue* obj) {
return obj->instack[0];
}
bool myQueueEmpty(MyQueue* obj) {
return obj->in==0 && obj->out==0;
}
void myQueueFree(MyQueue* obj) {
obj->in = 0;
obj->out = 0;
}
/**
* 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);
*/