思路:
很简单,栈:先入后出
队列:先入先出
那我们可以这样来玩:
一个用来进,一个用来出.
instack outstack
向instack放入1,2,3,4,5 此时栈instack排列肯定是这样 栈顶->5,4,3,2,1->栈底
此时把instack向outstack放, outstack排列 栈顶->1,2,3,4,5->栈底
然后往外吐就好了
showshowcode
typedef struct{
int* stk;
int stksize;
int stkcapacity;
}Stack;
Stack* stackCreate(int capacity){
Stack* ret = malloc(sizeof(Stack));
ret->stk = malloc(sizeof(Stack));
ret->stksize = 0;
ret->stkcapacity = capacity;
return ret;
}
void stackPush(Stack* obj,int x){
obj->stk[obj->stksize++] = x;
}
void stackPop(Stack* obj){
obj->stksize--;
}
int StackTop(Stack* obj){
return obj->stk[obj->stksize-1];
}
bool StackEmpty(Stack* obj){
return obj->stksize == 0;
}
void StackFree(Stack* obj){
free(obj);
}
typedef struct {
Stack* inStack;
Stack* outStack;
} MyQueue;
MyQueue* myQueueCreate() {
MyQueue* ret = malloc(sizeof(MyQueue));
ret->inStack = stackCreate(100);
ret->outStack = stackCreate(100);
return ret;
}
void in2out(MyQueue* obj){
while(!StackEmpty(obj->inStack)){
stackPush(obj->outStack, StackTop(obj->inStack));
stackPop(obj->inStack);
}
}
void myQueuePush(MyQueue* obj, int x) {
stackPush(obj->inStack,x);
}
int myQueuePop(MyQueue* obj) {
if(StackEmpty(obj->outStack)){
in2out(obj);
}
int x = StackTop(obj->outStack);
stackPop(obj->outStack);
return x;
}
int myQueuePeek(MyQueue* obj) {
if(StackEmpty(obj->outStack)){
in2out(obj);
}
return StackTop(obj->outStack);
}
bool myQueueEmpty(MyQueue* obj) {
return StackEmpty(obj->inStack) && StackEmpty(obj->outStack);
}
void myQueueFree(MyQueue* obj) {
StackFree(obj->inStack);
StackFree(obj->outStack);
}
/**
* 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);
*/