用两个栈实现队列

  用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )

思路:

  一个栈存储元素,一个栈辅助
  维护两个栈,第一个栈存储元素,第二个栈用于辅助操作

  根据栈的特性,第一个栈的底部元素是最后插入的元素,第一个栈的顶部元素是下一个被删除的元素。为了维护队列的特性,每次插入的元素应该在第一个栈的底部。因此每次插入元素时,若第一个栈内已经有元素,应将已有的全部元素依次弹出并压入第二个栈,然后将新元素压入第一个栈,最后将第二个栈内的全部元素依次弹出并压入第一个栈。经过上述操作,新插入的元素在第一个栈的底部,第一个栈内的其余元素的顺序和插入元素之前保持一致。

  删除元素时,若第一个栈非空,则直接从第一个栈内弹出一个元素并返回,若第一个栈为空,则返回 -1。

  另外维护队列的元素个数,用于判断队列是否为空。初始元素个数为 0。每次插入元素,元素个数加 1。每次删除元素,元素个数减 1。

#include<iostream>
#include<stack>
using namespace std;
stack<int> st1,st2;

//初始化,读取数据
void init(stack<int> & st1){
    int n,num;
    cin>>n;
    for (int i = 0; i < n; i++)
    {
        cin>>num;
        st1.push(num);
    }
}

//在对队尾加上元素,实际上是一个栈的栈顶
void appendTail(int value){
    st1.push(value);
}

//删除队列开头的元素
int deleteHead(){
    //队空
    if (st1.empty())
        return -1;
    //先把存储元素的栈反向保存到辅助栈st2,此时在栈顶的元素就是队头
    while (!st1.empty())
    {
        st2.push(st1.top());
        st1.pop();
    }
    //删除对头
    st2.pop();
    //保存到存储数据的栈st1
    while(!st2.empty()){
        st1.push(st2.top());
        st2.pop(); 
    }
    return 1;
}
//栈的遍历
void PrintValue(stack<int> st1){
    while(!st1.empty()){
        cout<<st1.top()<<" ";
        st1.pop();
    }
    cout<<endl;

}
//测试代码main()
int main(){
    init(st1);
    PrintValue( st1);
    appendTail(0);
    appendTail(-1);
    PrintValue( st1);
    deleteHead();
    PrintValue( st1);
}

 

 

 

 

class MyQueue {
    stack<int> st1, st2;

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

    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        st1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        if (st2.empty()) {
            while (!st1.empty()) {
                st2.push(st1.top());
                st1.pop();
            }
        }
        int ret = st2.top();
        st2.pop();
        return ret;
    }
    
    /** Get the front element. */
    int peek() {
        if (st2.empty()) {
            while (!st1.empty()) {
                st2.push(st1.top());
                st1.pop();
            }
        }
        return st2.top();
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        if (st2.empty()) {
            while (!st1.empty()) {
                st2.push(st1.top());
                st1.pop();
            }
        }
        return st2.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */

 

posted @ 2020-05-02 01:22  多发Paper哈  阅读(106)  评论(0编辑  收藏  举报
Live2D