[LeetCode]Implement Queue using Stacks
2015-07-19 08:59
197 查看
解题思路:
1,使用2个stack,一个叫PushStack,一个叫PopStack。
2,每当Queue新进来一个element时,就把它加入到PushStack,
3,当Queue执行Pop操作时,从PopStack取出element。
4,当PopStack为空时,把PushStack的元素一个一个的加入到PopStack
数据如何从pushStack到popStack
1,popStack必须为空,pushStack非空;
2,element = pushStack.top()
popStack.push(element)
pushStack.pop()
3,反复执行步骤2,直到pushStack为空
// 编译错误
1,Stack不是一个已经定义的类型。应该小写s的 stack
1,使用2个stack,一个叫PushStack,一个叫PopStack。
2,每当Queue新进来一个element时,就把它加入到PushStack,
3,当Queue执行Pop操作时,从PopStack取出element。
4,当PopStack为空时,把PushStack的元素一个一个的加入到PopStack
数据如何从pushStack到popStack
1,popStack必须为空,pushStack非空;
2,element = pushStack.top()
popStack.push(element)
pushStack.pop()
3,反复执行步骤2,直到pushStack为空
// 编译错误
1,Stack不是一个已经定义的类型。应该小写s的 stack
class Queue { public: // Push element x to the back of queue. void push(int x) { pushStack.push(x); } // Removes the element from in front of queue. void pop(void) { if (empty()){ // EXCLUDE IN THIS PROBLEM } if (popStack.empty() && !pushStack.empty()){ tansportation(); } return popStack.pop(); } // Get the front element. int peek(void) { if (empty()){ // EXCLUDE IN THIS PROBLEM } if (popStack.empty() && !pushStack.empty()){ tansportation(); } return popStack.top(); } // Return whether the queue is empty. bool empty(void) { return pushStack.empty() && popStack.empty(); } void tansportation(void){ if (popStack.empty() && !pushStack.empty()){ while(!pushStack.empty()){ int elem = pushStack.top(); popStack.push(elem); pushStack.pop(); } } } private: stack<int> pushStack; stack<int> popStack; };
相关文章推荐
- 玩转iOS 9的UIDynamics
- UITextView内容自适应高度&行间距的调转
- 【UI】自定义cell的步骤
- Stack and Queue 栈和队列
- rpmbuild 简单参数解释
- 075.Quick Sort 快速排序
- Message、Handler、Message Queue、Looper、Thread之间的关系(未完成)
- iOS开发——UI基础-屏幕适配
- Build Erlang-18.0 on Ubuntu-14.04
- UITextField只能输入数字以及输入数字和小数点并且小数点后保留2位小数
- UICollection view or Tableview 使用
- UIView
- Androd UI学习之ImageSwitcher
- UIKit框架结构
- UEFI简单的应用程序模块MyHelloWorld:C源文件/INF工程文件源码/简析[6]
- Android UI学习之Gallery
- StringBuffer 和StringBuilder的区别
- loadrunner使用web_custom_request post数据
- CEF Xilium.CefGlue 在当前窗口中打开所有链接(防止弹窗)
- 64位ubuntu在安装build-essential遇到依赖问题的解决办法