使用栈实现队列的下列操作:
push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。
解题思路:
队列是一种 先进先出的数据结构,队列中的元素都从后端入队,从前端出队。
实现队列最直观的方法是用链表,但在这篇文章里我会介绍另一个方法 - 使用栈。
栈是一种 后进先出的数据结构,栈中元素从栈顶压入,也从栈顶弹出。
为了满足队列的 FIFO 的特性,我们需要用到两个栈,用它们其中一个来反转元素的入队顺序,用另一个来存储元素的最终顺序。
pop
假如s1非空全部入栈到s2直接出栈即可
push
新的元素进入空的栈里,再将非空的出栈后入栈到另一个里面即可
#define MAXSIZE 100
typedef struct {
int a[MAXSIZE];
int Top;
} MyStack;
typedef struct {
MyStack s1;
MyStack s2;
} MyQueue;
/** Initialize your data structure here. */
MyQueue* myQueueCreate() {
MyQueue* obj = (MyQueue*)malloc(sizeof(MyQueue));
obj->s1.Top = -1;
obj->s2.Top = -1;
return obj;
}
/** Push element x to the back of queue. */
void myQueuePush(MyQueue* obj, int x) {
if(obj->s1.Top < MAXSIZE)
{
while(obj->s1.Top != -1)
{
obj->s2.a[++(obj->s2.Top)] = obj->s1.a[(obj->s1.Top)--];
}
obj->s1.a[++(obj->s1.Top)] = x;
while(obj->s2.Top != -1)
{
obj->s1.a[++(obj->s1.Top)] = obj->s2.a[(obj->s2.Top)--];
}
}
}
/** Removes the element from in front of queue and returns that element. */
int myQueuePop(MyQueue* obj) {
if(obj->s1.Top != -1)
return obj->s1.a[(obj->s1.Top)--];
return NULL;
}
/** Get the front element. */
int myQueuePeek(MyQueue* obj) {
if(obj->s1.Top != -1)
return obj->s1.a[obj->s1.Top];
return NULL;
}
/** Returns whether the queue is empty. */
bool myQueueEmpty(MyQueue* obj) {
if(obj->s1.Top == -1)
return true;
return false;
}
void myQueueFree(MyQueue* obj) {
free(obj);
}
/**
* 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);
*/