package java_jianzhioffer_algorithm;
/**
* 题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
* @author hexiaoli
*思考:队列特点是先进先出,栈是先进后出,所以需要两个进行操作。
*变形:两个队列实现一个栈
*/
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
class Node{
int val;
Node next = null;
public Node(int val) {
this.val = val;
}
}
public class Push_Pop {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
//如果 Stack2不为空,需要把stack2中的数据弹出再压入1中
while(!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
stack1.push(node);
}
public int pop() {
while(!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
return stack2.pop();
}
Queue<Integer> queue1 = new LinkedList<>();
Queue<Integer> queue2 = new LinkedList<>();
public void push_q(int node) {
//两个栈都为空时,优先考虑queue1
if (queue1.isEmpty()&&queue2.isEmpty()) {
queue1.add(node);
return;
}
//如果queue1为空,queue2有元素,直接放入queue2
if (queue1.isEmpty()) {
queue2.add(node);
return;
}
if (queue2.isEmpty()) {
queue1.add(node);
return;
}
}
public int pop_q() {
//两个栈都为空时,没有元素可以弹出
if (queue1.isEmpty()&&queue2.isEmpty()) {
try {
throw new Exception("stack is empty");
} catch (Exception e) {
}
}
//如果queue1为空,queue2有元素, 将queue2的元素依次放入queue1中,直到最后一个元素,我们弹出。
if (queue1.isEmpty()) {
while (queue2.size()>1) {
queue1.add(queue2.poll());
}
return queue2.poll();
}
if (queue2.isEmpty()) {
while (queue1.size()>1) {
queue2.add(queue1.poll());
}
return queue1.poll();
}
return (Integer) null;
}
public static void main(String[] args) {
Push_Pop pp = new Push_Pop();
pp.push(23);
pp.push(5);
pp.push(29);
System.out.println(pp.pop());
System.out.println(pp.pop());
System.out.println(pp.pop());
Push_Pop pp1 = new Push_Pop();
pp1.push_q(45);
pp1.push_q(4);
pp1.push_q(47);
System.out.println(pp1.pop_q());
System.out.println(pp1.pop_q());
System.out.println(pp1.pop_q());
}
}
剑指offer(5)用两个栈实现队列
猜你喜欢
转载自blog.csdn.net/hxl0925/article/details/89319450
今日推荐
周排行