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

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

  这道题面试的时候经常遇到,特此收录。全部代码来自《剑指offer》。

template 
class CQueue{public: CQueue(void); ~CQueue(void); void appendTail(const T &node); T deleteHead();private: stack
stack1; stack
stack2;};template
void CQueue
::appendTail(const T &node){ stack1.push(node);}template
T CQueue
::deleteHead(){ if (stack2.size() <= 0) { while (stack1.size() > 0) { T &data = stack1.top(); stack1.pop(); stack2.push(data); } } if(stack2.size() == 0) throw new exception("queue is empty"); T head = stack2.top(); stack2.pop(); return head;}

LeetCode上一道题 

 solution:

class Queue {private:    stack
stk1, stk2;public: // Push element x to the back of queue. void push(int x) { stk1.push(x); } // Removes the element from in front of queue. void pop(void) { peek(); stk2.pop(); } // Get the front element. int peek(void) { if (stk2.empty()) { while (stk1.size() > 0) { stk2.push(stk1.top()); stk1.pop(); } } return stk2.top(); } // Return whether the queue is empty. bool empty(void) { return stk1.empty() && stk2.empty(); }};

PS:

  两个队列实现一个栈

LeetCode上一道题: 

solution:    //使用一个队列实现栈

class Stack {private:    queue
que;public: // Push element x onto stack. void push(int x) { que.push(x); for (int i = 0; i < que.size()-1; ++i) { que.push(que.front()); que.pop(); } } // Removes the element on top of the stack. void pop() { que.pop(); } // Get the top element. int top() { return que.front(); } // Return whether the stack is empty. bool empty() { return que.empty(); }};

 

转载于:https://www.cnblogs.com/gattaca/p/4439265.html

你可能感兴趣的文章
SEO思考:逆水行舟 不进则退
查看>>
螺旋方阵
查看>>
nginx 跨域。。。掉坑里了,小心
查看>>
pyextend库-merge可迭代对象合并函数
查看>>
RHEL6 配置本地YUM源
查看>>
【算法】双线性插值
查看>>
c++中冒号(:)和双冒号(::)的用法
查看>>
作用域、闭包、模拟私有属性
查看>>
http tunnel使用简介(ZT)
查看>>
CefSharp的简单应用,制作自动学习视频软件(基于Chromium)
查看>>
Wdcp Apache、NGINX支持中文URL图片、文件名的解决方法
查看>>
非模态窗口的创建方法
查看>>
ORA-00445: Background Process "xxxx" Did Not Start After 120 Seconds
查看>>
转:美团数据库运维自动化系统
查看>>
数据分析之分布式爬虫---分布式爬虫架构
查看>>
直升机的革命---鱼鹰运输机
查看>>
模式识别和机器学习中的概率知识
查看>>
windows下搭建PHP环境
查看>>
Split()函数
查看>>
Linux 常用基本指令
查看>>