请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push
、pop
、peek
、empty
):
实现 MyQueue
类:
void push(int x)
将元素 x 推到队列的末尾int pop()
从队列的开头移除并返回元素int peek()
返回队列开头的元素boolean empty()
如果队列为空,返回true
;否则,返回false
说明:
- 你 只能 使用标准的栈操作 —— 也就是只有
push to top
,peek/pop from top
,size
, 和is empty
操作是合法的。 - 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
示例 1:
输入: ["MyQueue", "push", "push", "peek", "pop", "empty"] [[], [1], [2], [], [], []] 输出: [null, null, null, 1, 1, false] 解释: MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false
思路:
我们先定义栈,里面有一个数组,一个指针top,和最大承受能力值capacity,我们对栈进行初始化、入栈、出栈、判空、取栈顶、销毁栈操作,销毁栈时我们需要将数组free掉,此外,因为队列是先进先出,而栈是后进先出,要想用栈实现队列,我们需要定义两个栈,s1,s2。s1代表进入的栈,s2代表出来时的栈。我们初始化队列,先为其开辟空间,对队列里的两个栈进行初始化操作。入栈时直接进栈s1,则执行push(obj->s1,x),出栈时我们要考虑出来的栈是否为空,如果为空,我们将栈s1里的栈顶元素压入s2中,最终pop,取最前面的值也就是取栈顶s2,销毁队列时,直接销毁两个栈就可以。
代码:
typedef struct stack{
int *a;
int top;
int capacity;
}stack;
stack * Init(){
stack *s=malloc(sizeof(stack));
s->a=(int*)malloc(sizeof(int)*300);
s->top=0;
s->capacity=300;
return s;
}
void Push(stack *s,int x){
if(s->top==s->capacity){
return ;
}
else{
s->a[s->top]=x;
s->top++;
}
}
void Pop(stack *s){
if(s->top==0){
return ;
}
else{
s->top--;
}
}
int GetTop(stack *s){
return s->a[s->top-1];
}
bool Empty(stack *s){
if(s->top==0){
return true;
}
else{
return false;
}
}
void Free(stack *s){
free(s->a);
}
typedef struct {
stack *s1;
stack *s2;
} MyQueue;
MyQueue* myQueueCreate() {
MyQueue* p=malloc(sizeof(MyQueue));
p->s1=Init();
p->s2=Init();
return p;
}
void myQueuePush(MyQueue* obj, int x) {
Push(obj->s1,x);
}
int myQueuePop(MyQueue* obj) {
if(Empty(obj->s2)){
while(!Empty(obj->s1)){
Push(obj->s2,GetTop(obj->s1));
Pop(obj->s1);
}
}
int x=GetTop(obj->s2);
Pop(obj->s2);
return x;
}
int myQueuePeek(MyQueue* obj) {
if(Empty(obj->s2)){
while(!Empty(obj->s1)){
Push(obj->s2,GetTop(obj->s1));
Pop(obj->s1);
}
}
return GetTop(obj->s2);
}
bool myQueueEmpty(MyQueue* obj) {
return Empty(obj->s1)&&Empty(obj->s2);
}
void myQueueFree(MyQueue* obj) {
Free(obj->s1);
Free(obj->s2);
}