225.请你仅使用两个队列实现一个后入先出(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(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
- 这是个常规的操作题,不涉及什么算法。用两个队列来模仿栈,一个队列用来存储元素,另一个队列用来做一些辅助的转换。比如当要往入栈一个元素的话,则先入队到第二个队列,然后让第一个队列的元素依次出队入队到第二个队列,再让第二个队列的元素依次出队入队到第一个队列,这样的话第一个队列的队头元素永远是栈顶元素;当要出栈一个元素的话,就比较简单,直接让队列一出队一个元素即可。
typedef struct Queue {
int *data;
int head;
int rear;
int size;
} Queue;
Queue* queueCreate(int size) {
Queue *queue = (Queue*)malloc(sizeof(Queue));
queue->data = (int*)malloc(sizeof(int) * size);
queue->head = -1;
queue->rear = -1;
queue->size = size;
return queue;
}
void enQueue(Queue* obj, int x) {
if (obj->head == -1)
obj->head = 0;
obj->rear = (obj->rear + 1) % obj->size;
obj->data[obj->rear] = x;
}
int deQueue(Queue* obj) {
int a = obj->data[obj->head];
if (obj->head == obj->rear) {
obj->head = -1;
obj->rear = -1;
return a;
}
obj->head = (obj->head + 1) % (obj->size);
return a;
}
bool isQueueEmpty(Queue* obj) {
return obj->head == -1;
}
void freeQueue(Queue* obj) {
free(obj->data);
}
typedef struct {
Queue *queue1;
Queue *queue2;
} MyStack;
/** Initialize your data structure here. */
MyStack* myStackCreate() {
MyStack *mstack = (MyStack*)malloc(sizeof(MyStack));
mstack->queue1 = queueCreate(100);
mstack->queue2 = queueCreate(100);
return mstack;
}
/** Push element x onto stack. */
void myStackPush(MyStack* obj, int x) {
enQueue(obj->queue2, x);
while (!isQueueEmpty(obj->queue1)) {
enQueue(obj->queue2, deQueue(obj->queue1));
}
while (!isQueueEmpty(obj->queue2)) {
enQueue(obj->queue1,deQueue(obj->queue2));
}
}
/** Removes the element on top of the stack and returns that element. */
int myStackPop(MyStack* obj) {
return deQueue(obj->queue1);
}
/** Get the top element. */
int myStackTop(MyStack* obj) {
return obj->queue1->data[obj->queue1->head];
}
/** Returns whether the stack is empty. */
bool myStackEmpty(MyStack* obj) {
return isQueueEmpty(obj->queue1);
}
void myStackFree(MyStack* obj) {
free(obj->queue1);
free(obj->queue2);
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);
*/