7.用两个栈实现队列

  题目:用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead,分别完成在队列尾部插入结点和在队列头部删除结点的功能。

  思路:先将数据压入stack1中。删除时,把stack1所有的数据弹出到stack2压入,然后每次要删除第一个结点,就从stack2弹出;添加时,直接压入到stack1。

  测试用例:
  1.往空的队列里添加、删除元素。
  2.往非空的队列里添加、删除元素
  3.连续删除元素直至队列为空。

  代码:

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

template <typename T> class CQueue
{
public :
  CQueue(void);
  ~CQueue(void);

  //在队列末尾添加一个结点
  void appendTail(const T& node);

  //删除队列的头结点
  T deleteHead();

private:
    stack<T> stack1;
    stack<T> stack2;

};

template<typename T> CQueue<T>::CQueue(void)
{

}

template<typename T> CQueue<T>::~CQueue(void)
{

}

template<typename T> void CQueue<T>::appendTail(const T& element)
{
    stack1.push(element);
}

template<typename T> T CQueue<T>::deleteHead()
{
    if (stack2.size() <= 0)   //当stack2为空时,需将stack1所以元素弹出到stack2
    {
        while (stack1.size() > 0)
        {
            T& data = stack1.top(); //指向栈顶元素
            stack1.pop();
            stack2.push(data);
        }
    }

    if (stack2.size() == 0)
    {
        throw new exception();
    }

    T head = stack2.top();
    stack2.pop();

    return head;
}

void test(char actual, char expected)
{
    if (actual == expected)
    {
        cout << "Test Passed" << endl;
    }
    else
    {
        cout << "Test failed" << endl;
    }
}

int main()
{
    CQueue<char> queue;

    queue.appendTail('a');
    queue.appendTail('b');
    queue.appendTail('c');

    char head = queue.deleteHead();
    test(head, 'a');

    head = queue.deleteHead();
    test(head, 'b');

    queue.appendTail('d');
    head = queue.deleteHead();
    test(head, 'c');

    queue.appendTail('e');
    head = queue.deleteHead();
    test(head, 'd');

    head = queue.deleteHead();
    test(head, 'e');

    return 0;
}

 

  相关题目:用两个队列实现一个栈。
  
  思路:删除时,先从queue1中依次删除元素a、b并插入到queue2中,再从queue1中删除元素c。这就相当于从栈中弹出元素c。压入时,直接压入queue1。

171658_r4b5_2746716.png

 

 

转载于:https://my.oschina.net/134596/blog/1789989

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值