题目描述
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
示例
输入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]
解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/implement-stack-using-queues
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目提示
1 <= x <= 9
最多调用100 次 push、pop、top 和 empty
每次调用 pop 和 top 都保证栈不为空
思路
做题思路基本与用栈实现队列一致,但在写pop函数时,要注意队列是先入先出,而栈是后入先出。
代码
typedef struct
{
int in[100],out[100];
int intop,outtop;
} MyStack;
MyStack* myStackCreate() {
MyStack *stack=(MyStack*)malloc(sizeof(MyStack));//申请栈的空间
//初始化两个队列的下标
stack->intop=0;
stack->outtop=0;
return stack;
}
void myStackPush(MyStack* obj, int x)
{
obj->in[obj->intop++]=x;
}
int myStackPop(MyStack* obj)
{
int inindex,outindex;
inindex=0;
outindex=obj->outtop;
if(obj->outtop==0)
{
while(inindex<obj->intop)
{
obj->out[outindex++]=obj->in[inindex++];
}
}
int tmp=obj->out[--outindex];
int i=0;
inindex=0;
while(i<outindex)
{
obj->in[inindex++]=obj->out[i++];
}
obj->outtop=0;
obj->intop=inindex;
return tmp;
}
int myStackTop(MyStack* obj)
{
return obj->in[obj->intop-1];
}
bool myStackEmpty(MyStack* obj)
{
if(obj->intop==0&&obj->outtop==0)
return true;
else
return false;
}
void myStackFree(MyStack* obj)
{
free(obj);
}
/**
* Your MyStack struct will be instantiated and called as such:
* MyStack* obj = myStackCreate();
* myStackPush(obj, x);
* int param_2 = myStackPop(obj);
* int param_3 = myStackTop(obj);
* bool param_4 = myStackEmpty(obj);
* myStackFree(obj);
*/
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/implement-stack-using-queues