Implement Queue by Two Stacks用栈实现队列
Description
As the title described, you should only use two stacks to implement a queue’s actions.
The queue should support push(element), pop() and top() where pop is pop the first(a.k.a front) element in the queue.
Both pop and top methods should return the value of first element.
public class MyQueue {
private Stack<Integer> stack1 ;
private Stack<Integer> stack2 ;
public MyQueue() {
// do intialization if necessary
stack1 = new Stack<Integer>() ;
stack2 = new Stack<Integer>() ;
}
/*
* @param element: An integer
* @return: nothing
*/
public void push(int element) {
// write your code here
stack1.push(element) ;
}
/*
* @return: An integer
*/
public int pop() {
// write your code here
if(stack2.isEmpty() == true){
while(! stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop() ;
}
/*
* @return: An integer
*/
public int top() {
// write your code here
if(stack2.isEmpty() == true){
while(! stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.peek() ;
}
}
这篇博客介绍如何利用两个栈来实现一个基本的队列数据结构。push方法将元素压入栈1,当需要弹出或查看队列头部元素时,如果栈2为空,则将栈1的所有元素依次弹出并压入栈2,然后通过栈2进行pop或top操作。这种方法巧妙地利用了栈的后进先出特性来模拟队列的先进先出原则。
274

被折叠的 条评论
为什么被折叠?



