前言:这道题很简单,第一次做时,提交了一次;第二次做时,连续提交了三次。而且代码也变的很烂.
不上心什么都做不好
1. 基本想法
假设两个栈分别人stack1 和stack2
- 进栈时,进栈stack1
- 出栈时,
- 如果stack2栈不为空,则将stack2的栈顶元素作为返回元素
- 如果stack2为空,但是stack1不为空,那么将stack1栈中的元素push进stack2,而后取出stack2的栈顶元素作为返回元素
Note: 特殊情况处理.
2.代码
二代代码
class Solution { public: void push(int node) { stack1.push(node); } int pop() { if(stack1.empty() && stack2.empty()){ cout<<"queue is empty"<<endl; return 0; } int t; if(stack2.size()){ t=stack2.top(); stack2.pop(); }else{ while(stack1.size()){ t=stack1.top(); stack1.pop(); stack2.push(t); } t=stack2.top(); stack2.pop(); } return t; } private: stack<int> stack1; stack<int> stack2; };
初代代码
class Solution { public: void push(int node) { stack1.push(node); } int pop() { int t,_size; _size=stack2.size(); while( _size==0 && stack1.size()){ t=stack1.top(); stack2.push(t); stack1.pop(); } t=stack2.top(); stack2.pop(); return t; } private: stack<int> stack1; stack<int> stack2; };