两个栈实现队列

先入后出的栈构建先入先出的队列

queue.h

//用两个栈实现队列
#include <iostream>
#include <stack>
using namespace std;

class MyQueue {
public:
    MyQueue();
    ~MyQueue();

    bool empty() const;
    void append(const int node);
    int size() const;
    int front();
    int back() const;
    int removeHead(); 

private:
    stack<int> m_stack1; //主栈
    stack<int> m_stack2; //辅助栈
};

queue.cpp

//用两个栈实现队列
#include "queue.h"

MyQueue::MyQueue()
{
}

MyQueue::~MyQueue()
{
}

bool MyQueue::empty() const
{
    return m_stack1.empty();
}

void MyQueue::append(const int node)
{
    //将元素压栈到主栈
    m_stack1.push(node);
}

int MyQueue::size() const
{
    //获取主栈元素个数
    return m_stack1.size();
}

int MyQueue::front()
{
    int head;
    while(m_stack2.size() > 0)
    {
        m_stack2.pop();
    }
    
    while(m_stack1.size() > 0)
    {
        int data = m_stack1.top();
        m_stack1.pop();
        m_stack2.push(data);
    }
    
    if(m_stack2.empty())
    {
        cout << "queue is empty!";
    }
    
    head = m_stack2.top();

    while(m_stack2.size() > 0)
    {
        int data = m_stack2.top();
        m_stack2.pop();
        m_stack1.push(data);
    }

    return head;
}

int MyQueue::back() const
{
    return m_stack1.top();
}

int MyQueue::removeHead()
{
    int head;

    while(m_stack2.size() > 0)
    {
        m_stack2.pop();
    }

    while(m_stack1.size() > 0)
    {
        int data = m_stack1.top();
        m_stack1.pop();
        m_stack2.push(data);
    }

    if(m_stack2.empty())
    {
        cout << "queue is empty!";
    }

    head = m_stack2.top();
    m_stack2.pop();

    while(m_stack2.size() > 0)
    {
        int data = m_stack2.top();
        m_stack2.pop();
        m_stack1.push(data);
    }

    return head;
}

main.cpp

#include "queue.h"

void Test()
{
    MyQueue queue;
    queue.append(10);
    queue.append(11);
    queue.append(12);
    queue.append(13);
    queue.append(14);
    queue.append(15);
    queue.append(16);
    queue.append(17);

    int head = queue.removeHead();
    cout << "head of queue: " << head << endl;

    int head2 = queue.front();
    cout << "head of queue: " << head2 << endl;

    int back = queue.back();
    cout << "back of queue: " << back << endl;

    while(queue.size())
    {
        int head = queue.removeHead();
        cout << head << endl;
    }
}

int main()
{
    Test();

    return 0;
}

 makefile

queue : main.cpp queue.cpp queue.h
	g++ main.cpp queue.cpp -o queue

clean : 
	rm queue

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值