标签:
栈 : 先进后出!
队列 : 先进先出!
那么怎么用栈来实现队列呢?
第一版:
push() : 直接将元素进栈1;
pop() : 栈1 元素进栈2 ,栈2 出元素 ! 出完将元素还给栈1.
总结:队列要求先进先出 , 那越先进的元素 就在栈1的越下面 , 这样才能保证越先进的元素 在 栈2的越上面. 所以每次pop()需要现将栈1中元素全部挪到栈2 , 出完 栈2 需要把元素还剩下的元素还回去!
//用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
package wj;
import java.util.Stack;
/**
* Created by wangjia on 2015/8/10
*/
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
//进队
public void push(int node) {
stack1.push(node);
}
//出队
public int pop() {
while(!stack1.empty()){
stack2.push(stack1.pop());
}
int result= stack2.pop();
while (stack2.empty()){
stack1.push(stack2.pop());
}
return result;
}
}
第二版:
第一版虽然正确,但是感觉有些繁琐!!!总体思路是没有错的.
经过分析之后,发现上诉步骤可以省略一些.栈2中的元素肯定是比栈1的中元素先进的!那是否有必要还回去呢?其实不用!
当栈2中有元素时,直接出栈就行了!!当栈2木有元素时,从栈1的底部拿.
package wj;
import java.util.Stack;
/**
* Created by wangjia on 2015/8/10
*/
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
//出队
public int pop() {
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
标签:
原文地址:http://my.oschina.net/dadou/blog/490103