1、两个队列实现栈
思路:有两个队列,一个队列data,一个辅助队列help,我们只把数字加入到data中,在从data弹出元素之前,把最后加入元素之前的元素先全部压进help队列,然后data再做弹栈操作,就可以使得弹出的是最后一个压入的元素。接着,data和help交换引用,data将除了最后一个元素以外的所有元素全部压进help中,再做弹栈操作。以此类推。
import java.util.LinkedList;
import java.util.Queue;
public class Test{
private Queue<Integer> data;
private Queue<Integer> help;
public Test() {
this.data=new LinkedList<Integer>();
this.help=new LinkedList<Integer>();
}
public void push(int obj) {
data.add(obj);
}
public int peek() {
if(data.isEmpty()) {
throw new ArrayIndexOutOfBoundsException("The stack is empty");
}
while(data.size()>1) {
help.add(data.poll());
}
int res=data.poll();
help.add(res);//不抹除该res
swap();
return res;
}
public int pop() {
if(data.isEmpty()) {
throw new ArrayIndexOutOfBoundsException("The stack is empty");
}
while(data.size()>1) {
help.add(data.poll());
}
int res=data.poll();
swap();
return res;
}
public void swap() {
Queue<Integer> tmp=help;
help=data;
data=tmp;
}
public static void main(String[] args) {
Test t=new Test();
t.push(1);
t.push(3);
t.push(5);
t.push(7);
System.out.println(t.pop());
System.out.println(t.pop());
}
}
输出:
7
5
2、两个栈实现队列
思路:两个栈,一个push栈专门用来压栈,一个pop栈专门用来弹栈。将数字依次压入push栈,push栈再将栈中元素全部倒入pop栈,通过pop栈弹出即可实现队列结构。
但有两个原则需要遵循:
1)push栈若要向pop栈倒东西,一定要一次性倒完,不要倒一半。否则会导致出队列顺序出错。
2)如果pop栈有东西push栈一定不要向pop栈倒东西。
import java.util.Stack;
public class Test{
private Stack<Integer> push;
private Stack<Integer> pop;
public Test() {
this.push=new Stack<Integer>();
this.pop=new Stack<Integer>();
}
public void push(int obj) {
push.push(obj);
dao();//什么时候发生倒数据的行为都无所谓,只要满足两个原则就不会出错
}
public int peek() {
if(pop.isEmpty()&&push.isEmpty()) {
throw new ArrayIndexOutOfBoundsException("The stack is empty");
}
dao();
return pop.peek();
}
public int poll() {
if(pop.isEmpty()&&push.isEmpty()) {
throw new ArrayIndexOutOfBoundsException("The stack is empty");
}
dao();
return pop.pop();
}
//倒数据的行为要遵循以下两个原则
public void dao() {
if(!pop.isEmpty()) {
return ;
}
while(!push.isEmpty()) {
pop.push(push.pop());
}
}
public static void main(String[] args) {
Test t=new Test();
t.push(1);
t.push(3);
t.push(5);
t.push(7);
System.out.println(t.poll());
System.out.println(t.poll());
}
}
输出:
1
3