博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
7.用两个栈实现队列
阅读量:6861 次
发布时间:2019-06-26

本文共 1659 字,大约阅读时间需要 5 分钟。

  hot3.png

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

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

  测试用例:

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

  代码:

#include
#include
#include
using namespace std;template
class CQueue{public : CQueue(void); ~CQueue(void); //在队列末尾添加一个结点 void appendTail(const T& node); //删除队列的头结点 T deleteHead();private: stack
stack1; stack
stack2;};template
CQueue
::CQueue(void){}template
CQueue
::~CQueue(void){}template
void CQueue
::appendTail(const T& element){ stack1.push(element);}template
T CQueue
::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
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

你可能感兴趣的文章
spring常用注解
查看>>
Material Menu
查看>>
Win8 环境变量位置
查看>>
margin负值的应用总结
查看>>
分页查询
查看>>
iLBC
查看>>
Linux 本地yum源搭建和网络yum源搭建
查看>>
HDU 5781 ATM Mechine
查看>>
使用Nginx搭建Tomcat9集群,Redis实现Session共享
查看>>
Extjs4.1 序列化和反序列化
查看>>
iOS self 和 super 学习
查看>>
js的闭包的一个示例说明
查看>>
bin/sh failed with exit code 1
查看>>
《梦幻西游》打响反盗号战役:为2亿玩家提供360安全武器
查看>>
Silverlight面向客户端,HTML5面向Web
查看>>
微软拟向互联网开发商提供免费IIS 服务器
查看>>
seajs和requirejs对比;node初识
查看>>
Python笔记总结week1
查看>>
c#中使用NetCDF存储二维数据的读写操作简单应用
查看>>
linux网络相关命令使用
查看>>