一、题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
二、思路分析
Push:直接添加元素到栈1中;
Pop:当元素要出栈时,把栈1中的元素全部pop到栈2中,再从栈2弹出栈顶元素。若栈1为空,直接弹出栈2栈顶元素。
三、实现代码
import java.util.Stack;
/**
* @AUTHOR:0416
* @DESCRIPTION: use two stack to implement the queue
* @DATE:2019/10/18
**/
public class ImpQueueByTwoStack {
private Stack<Integer> stack1 = new Stack<Integer>();
private Stack<Integer> stack2 = new Stack<Integer>();
public void Push(int node){
stack1.push(node);
}
public int Pop(){
if(!stack2.isEmpty()){
return stack2.pop();
}else {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
if(!stack2.isEmpty()){
return stack2.pop();
}else{
throw new NullPointerException();
}
}
public static void main(String[] args) {
ImpQueueByTwoStack queue = new ImpQueueByTwoStack();
queue.Push(1);
queue.Push(2);
queue.Push(3);
queue.Push(4);
queue.Push(5);
queue.Push(6);
System.out.println(queue.Pop());
System.out.println(queue.Pop());
queue.Push(7);
queue.Push(8);
queue.Push(9);
System.out.println(queue.Pop());
System.out.println(queue.Pop());
}
}
四、相关题目:用两个队列实现栈
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* @AUTHOR:0416
* @DESCRIPTION:use two queue to implement the stack
* @DATE:2019/10/20
**/
public class ImpStackByTwoQueue {
private Queue queueOne = new LinkedBlockingQueue();
private Queue queueTwo = new LinkedBlockingQueue();
public void append(Integer integer){
queueOne.offer(integer);
}
public Integer delete(){
while(queueOne.size() > 1){
queueTwo.offer(queueOne.poll());
}
if(queueOne.size() == 1){
return (Integer)queueOne.poll();
}
while(queueTwo.size() > 1){
queueOne.offer(queueTwo.poll());
}
if(queueTwo.size() == 1){
return (Integer)queueTwo.poll();
}
return null;
}
public static void main(String[] args) {
ImpStackByTwoQueue stack = new ImpStackByTwoQueue();
stack.append(1);
stack.append(2);
stack.append(3);
stack.append(4);
stack.append(5);
stack.append(6);
System.out.println(stack.delete());
System.out.println(stack.delete());
stack.append(7);
stack.append(8);
stack.append(9);
System.out.println(stack.delete());
System.out.println(stack.delete());
}
}