1.用两个栈实现队列
队列声明如下,实现它的两个函数push()和POP(),分别完成在队列尾部插入结点和在队列头部删除结点的功能。
算法思想:定义两个栈,分别为stack1与stack2。push()进队列操作,即为结点直接进入stack1即可。pop出队列操作的步骤:如果stack2为空时,把stack1中的元素逐个弹出并压入stack2.。由于先进入队列的元素被压到stack1的底端,经过弹出和压入之后就处于stack2的顶端了,又可以直接弹出了。结合具体的示例如下图所示,
实现代码:
import java.util.Stack;
public class StackToQueue {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
if(stack2.isEmpty()){
try {
throw new Exception("queue is empty.");
} catch (Exception e) {
}
}
return stack2.pop();
}
public static void main(String[] args) {
StackToQueue s1 = new StackToQueue();
s1.push(1);
s1.push(2);
s1.push(3);
s1.push(4);
System.out.println(s1.pop());
System.out.println(s1.pop());
s1.push(5);
System.out.println(s1.pop());
System.out.println(s1.pop());
System.out.println(s1.pop());
}
}