剑指offer——用两个栈实现队列
题目
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
实现及原理
- 栈,具有先进后出的特点;而队列具有先进先出的特点
- 通过两个栈实现队列的特点,那么一个栈就需要作为压入栈,一个栈作为弹出栈。压入数据进压入栈,弹出数据从弹出栈出。
- 在弹出数据时,需要判断弹出栈中是否还有数据,若还有剩余数据未被弹出,则直接弹出数据。否则,需要从压入栈中将数据导入弹出栈,再进行数据的弹出。
参考代码
import java.util.Stack;
/**
*
* @author LXH
*
*/
public class StackToQueue {
// 压入栈
Stack<Integer> stack1 = new Stack<Integer>();
// 弹出栈
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
// 如果两个队列均为空,则不能在进行弹出操作,抛出运行时异常。
if(stack1.empty() && stack2.empty()) {
throw new RuntimeException("Queue is Empty");
}
// 若弹出栈不为空,则直接从弹出站中弹出相应的数据即可。
if(!stack2.empty()) {
return stack2.pop();
}
// 否则,需要将数据从压入栈中倒进弹出栈。
while(!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
return stack2.pop();
}
public static void main(String[] args) {
StackToQueue stackToQueue = new StackToQueue();
stackToQueue.push(0);
stackToQueue.push(1);
stackToQueue.push(2);
stackToQueue.push(3);
stackToQueue.push(4);
stackToQueue.push(5);
stackToQueue.push(6);
System.out.println(stackToQueue.pop());
System.out.println(stackToQueue.pop());
System.out.println(stackToQueue.pop());
System.out.println(stackToQueue.pop());
System.out.println(stackToQueue.pop());
}
}
运行结果
本题作为剑指offer中的题目,还是很受面试官们的青睐的,前一段时间的京东面试官就问到了这个题目的变形题目,不过万变不离其宗。把握住其中心思想,相信其他变形题目大家也是可以解决的。
还没有评论,来说两句吧...