题目一:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
利用两个栈s1和s2模拟一个队列。当需要向队列中插入一个元素,用s1来存放已输入的元素,即s1执行入栈操作。当需要出队的时候,需要对s2进行出栈的操作。由于从栈中取出的元素的顺序是逆序,所以必须将s1中的所有元素全部出栈并入栈到s2中,再在s2中执行出栈操作,即可实现出队列操作,而在执行此操作之前必须判断s2是否为空。
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(!stack2.isEmpty()){
return stack2.pop();
}
while (!stack1.isEmpty())
{
int temp=stack1.pop();
stack2.push(temp);
}
return stack2.pop();
}
}
题目二:使用两个队列实现一个栈
压入:就是简单的直接压入一个队列中
弹出(或者取出栈顶元素):可以先从输入队列中依次删除元素并插入队列2中,再从输入队列中删除最后一个元素,这就相当于从栈中弹出元素。然后再把这个队列2中的元素再放回队列(输入队列中),就这样相互交换。
import java.util.Queue;
import java.util.LinkedList;
class MyStack {
private Queue<Integer> q1; //输入队列
private Queue<Integer> q2; //输出队列
private Integer top;
/** Initialize your data structure here. */
public MyStack() {
q1=new LinkedList<>();
q2=new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
q1.add(x);
}
/** Removes the element on top of the stack and returns that element. */
//移除栈顶元素
public int pop() {
while(q1.size()>1){
int temp=q1.poll();
q2.add(temp);
}
int value=q1.poll();
while(q2.size()>0){
q1.add(q2.poll());
}
return value;
}
/** Get the top element. */
public int top() {
while(q1.size()>1){
int temp=q1.poll();
q2.add(temp);
}
int value=q1.poll();
q2.add(value);
while(q2.size()>0){
q1.add(q2.poll());
}
return value;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty();
}
}