题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
package code;
//题目描述:
// 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
//思路:
// 第一个栈时主要的用来模拟队列,第二个栈用来辅助
// 进队列时将数据插到队尾,相当于把数据压入第一个栈,
// 出队列时需要取出队头,可以把第一个栈的内容倒过来放到第二个栈,这样第二个栈的栈顶就是队头了。
// 将队头取出来后再将第二个栈剩下的内容倒过来放到第一个栈去,相当于出队列后的样子
import java.util.Stack;
public class Offer04
{
public static void main(String[] args)
{
Offer04 offer = new Offer04();
offer.push(1);
offer.push(2);
offer.push(3);
offer.pop();
offer.print();
}
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node)
{
stack1.push(node);
}
public int pop()
{
while(!stack1.isEmpty())
stack2.push(stack1.pop());
int first = stack2.pop();
while(!stack2.isEmpty())
stack1.push(stack2.pop());
return first;
}
public void print()
{//打印队列内容(按出队列顺序打印)
while(!stack1.isEmpty())
{
stack2.push(stack1.pop());
}
while(!stack2.isEmpty())
{
System.out.println(stack2.peek());
stack1.push(stack2.pop());
}
}
}