嵌入式Linux C++练习6——类模板2

定义一个模板栈,用栈实现队列的功能(push,pop,先进先出)

思路:同C语言两个栈实现一个队列一样,构建一个辅助栈,执行pop操作时,先将数据从主栈pop出push进辅助栈,再从辅助栈中pop出,没什么难度的题目

#include <iostream>
#include <stack>
using namespace std;

//思路:同C语言两个栈实现一个队列一样,构建一个辅助栈,
//执行pop操作时,先将数据从主栈pop出push进辅助栈,
//再从辅助栈中pop出
template <typename T>
class MyQueue
{
    
    
private:
    stack<T> stack1; //主栈
    stack<T> stack2; //辅助栈

public:
    void mypush(T data); //入栈
    void mypop(); //弹栈
};

template <typename T>
void MyQueue<T>::mypush(T data)
{
    
    
    stack1.push(data);
    cout << "弹入" << data << endl;
}

template <typename T>
void MyQueue<T>::mypop()
{
    
    
    if (stack1.size() <= 0)
    {
    
    
        cout << "栈空!" << endl;
        return;
    }
    while (stack1.size() > 0)
    {
    
    
        stack2.push(stack1.top());
        stack1.pop();
    }
    T head = stack2.top();
    stack2.pop();

    while (stack2.size() > 0)
    {
    
    
        stack1.push(stack2.top());
        stack2.pop();
    }
    cout << "弹出" << head << endl;
}

int main()
{
    
    
    MyQueue<int> queue1;
    MyQueue<char> queue2;

    queue1.mypush(1);
    queue1.mypush(2);
    queue1.mypush(3);
    queue1.mypush(4);

    queue1.mypop();
    queue1.mypop();

    queue2.mypush('a');
    queue2.mypush('b');
    queue2.mypush('c');
    queue2.mypush('d');

    queue2.mypop();
    queue2.mypop();

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45792897/article/details/119575830