解题思路
利用双栈实现队列,
特别要理解in2out的精髓所在
妙啊
代码
//栈结构
typedef struct {
int* stk;//指针
int stkSize;//栈顶
int stkCapacity;//栈容量
} Stack;
Stack* stackCreate(int cpacity) {
Stack* ret = malloc(sizeof(Stack));//初始化
ret->stk = malloc(sizeof(int) * cpacity);//初始化
ret->stkSize = 0;//栈顶
ret->stkCapacity = cpacity;//容量
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;//空返回0,不空返回1
}
//释放指针
void stackFree(Stack* obj) {
free(obj->stk);
}
typedef struct {
int* inStack;//入栈
int* outStack;//出栈
} MyQueue;
/** Initialize your data structure here. */
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);//入栈size改变
}
}
/** Push element x to the back of queue. */
void myQueuePush(MyQueue* obj, int x) {
stackPush(obj->inStack, x);//入队列,也就是数值进入栈
}
/** Removes the element from in front of queue and returns that element. */
int myQueuePop(MyQueue* obj) {
if (stackEmpty(obj->outStack)) {//出栈没有空
in2out(obj);//将入栈的顶转移到出栈,该方法会将栈的顺序倒置,恰好是队列的顺序
}
int x = stackTop(obj->outStack);//获取队列的第一个数
stackPop(obj->outStack);//改变出栈的大小
return x;
}
/** Get the front element. */
int myQueuePeek(MyQueue* obj) {
if (stackEmpty(obj->outStack)) {
in2out(obj);
}
return stackTop(obj->outStack);//返回队列第一个数(谁先弹出谁是第一个)
}
/** Returns whether the queue is empty. */
bool myQueueEmpty(MyQueue* obj) {
return stackEmpty(obj->inStack) && stackEmpty(obj->outStack);
}
void myQueueFree(MyQueue* obj) {
stackFree(obj->inStack);
stackFree(obj->outStack);
}