用队列实现栈
题目描述:
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈 的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false
注意:
你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
题目来源:力扣(LeetCode)
思路:
两个队列
往不为空的队列如数据
保持另一个队列为空
出数据,前size-1个导入空数据,删最后一个
typedef struct {buwei
Queue q1;
Queue q2;
} MyStack;
/** Initialize your data structure here. */
MyStack* myStackCreate() {
MyStack*p = (MyStack*)malloc(sizeof(MyStack));
QueueInit(&p->q1);
QueueInit(&p->q2);
}
/** Push element x onto stack. */
void myStackPush(MyStack* obj, int x) {
if(!QueueEmpty(&obj->q1))
QueuePush(&obj->q1,x);
else
QueuePush(&obj->q2,x);
}
/** Removes the element on top of the stack and returns that element. */
int myStackPop(MyStack* obj) {
if (!QueueEmpty(obj->q1)) {
Queue*pEmpty = &obj->q1;
Queue*pNoEmpty = &obj->q2;
if(!QueueEmpty(&obj->q1)
{
pEmpty = &obj->q2;
PNoEmpty = &obj->q1;
}
while (QueueSize(pNoEmpty)>1) {
QueuePush(pEmpty,QueueFront(pNoEmpty));
QueuePop(pNoEmpty);
}
int front = QueueFront(pNoEmpty);
QueuePop(pNoEmpty);
return front;
}
/** Get the top element. */
int myStackTop(MyStack* obj) {
if(!QueueEmpty(&obj->q1))
return QueueBack(&obj->q1);
else
return QueueBack(&obj->q2);
}
/** Returns whether the stack is empty. */
bool myStackEmpty(MyStack* obj) {
return QueueEmpty(&obj->q1)&&QueueEmpty(&obj->q2);
}
void myStackFree(MyStack* obj) {
QueueDestory(&obj->q1);
QueueDestory(&obj->q2);
free(obj);
}
注:代码中的函数在我的另一篇文章中实现队列