【数据结构】——堆栈之间相互实现的问题

现在,大家可能对堆先进后出,队列先进先出的结构以及很熟悉了吧,这篇文章,我们主要来讲一下用c++如何用堆实现队列,用队列来实现栈~
一、用一个队列来实现栈结构

在这里插入图片描述

思路:
& 本题实质上就是使用先进先出的原则实现先进后出的结构
& 所以,C++实现,用一个队列即可实现,只用将n-1队尾元素拿出来头插,再出队尾元素,或是删除队尾元素,即可实现一个栈先进后出的功能

代码实现:

class MyStack {
public:
    /** Initialize your data structure here. */
    MyStack() {

    }
    /** Push element x onto stack. */
    void push(int x) {
        q1.push(x);
    }
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int size = q1.size() - 1;
        for(size_t i = 0; i < size ;++i)
        {
            q1.push(q1.front());
            //把队列前面的元素全部拿出来重新入队
            q1.pop();
        }
        //此时栈顶元素就是队列的队头元素
        int front = q1.front();
        //出队
        q1.pop();
        return front;
    }
    /** Get the top element. */
    int top() {
        return q1.back();
    }
    /** Returns whether the stack is empty. */
    bool empty() {
        if(q1.empty())
            return true;
        else
            return false;
    }
    private:
    queue<int> q1;
};

二、用一个栈实现队列结构

在这里插入图片描述

思路:
& 实质上是使用先进后出的性质实现先进先出的结构
& 所以,用c++实现,一个栈就可以。只用将栈顶n-1个元素拿出来入队,然后返回栈底的值,再把队列里面的元素出队入栈。重复上述操作即可。

代码实现:



class MyQueue {
public:
    stack<int> s;
    stack<int> h;
    /** Initialize your data structure here. */
    MyQueue() {
    }
    /** Push element x to the back of queue. */
    void push(int x) {
        s.push(x);
    }
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        while(s.size() != 1)
        {
            h.push(s.top());
            s.pop();
        }
        int ans = s.top();
        s.pop();
        while(!h.empty())
        {
            s.push(h.top());
            h.pop();
        }
        return ans;
    }

    /** Get the front element. */
    int peek() {
        while(s.size() != 1)
        {
            h.push(s.top());
            s.pop();
        }
        int ans = s.top();
        while(!h.empty())
        {
            s.push(h.top());
            h.pop();
        }
        return ans;

    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return s.empty();
    }
};
发布了62 篇原创文章 · 获赞 7 · 访问量 2583

猜你喜欢

转载自blog.csdn.net/qq_43412060/article/details/104333877