两个队列生成一个栈
其他
2018-05-08 23:00:00
阅读次数: 2
package 队列;
/** * 两个队列实现一个栈 * * 思路:队列1和队列2在任意时刻至少有一个为空,即如果有元素,所有元素只能在一个队列中。当有元素需要插入时,将元素插入到 * 空队列中,并将另一非空队列的所有元素全部转移到该队列中,于是,插入的元素添加到了对列的最前面 * * @author Administrator * */ public class Stack {
Queue queue1 = new Queue();
Queue queue2 = new Queue();
/**
* 判断非空
* @return
*/
public boolean isEmpty(){
return queue1.isEmpty() && queue2.isEmpty();
}
/**
* 添加元素
*/
public void push(int data){
if(queue1.isEmpty()){
queue1.push(data);
while(!queue2.isEmpty()){
queue1.push(queue2.pop());
}
}else{
queue2.push(data);
while(!queue1.isEmpty()){
queue2.push(queue1.pop());
}
}
}
/**
* 从栈取元素
* @return
*/
public Integer pop(){
if(queue1.isEmpty()&&queue2.isEmpty()){
return null;
}
if(!queue1.isEmpty()){
return queue1.pop();
}else{
return queue2.pop();
}
}
/**
* 取峰值
* @return
*/
public Integer peek(){
if(queue1.isEmpty()&&queue2.isEmpty()){
return null;
}
if(!queue1.isEmpty()){
return queue1.peek();
}else{
return queue2.peek();
}
}
/**
* 主函数
* @param args
*/
public static void main(String[] args) {
Stack stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
while(!stack.isEmpty()){
System.out.println(stack.pop());
}
}
} |
转载自blog.csdn.net/lz1170063911/article/details/80097001