用栈实现队列

使用栈实现队列的下列操作:

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);
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值