第一部分:栈实现队列
已知:入栈/队列顺序 A B C D E F G
栈 : 先入后出 G F E D C B A
队列:先入先出 A B C D E F G
可以用两个栈a,b来实现队列,放数据时将数据都存在a栈中,移除数据时将
a栈的数据都移除到b栈中
代码实现:
public class DuLlieImpl {
static Stack stack1 = new Stack();
static Stack stack2 = new Stack();
public static void main(String[] args) {
DuLlieImpl queue = new DuLlieImpl();
queue.push("aaa");//调用push算法,使得数据都进入stack1
queue.push("bbb");
queue.push("ccc");
queue.push("ddd");
System.out.println(queue.pop());//移除数据
System.out.println(queue.pop());
System.out.println(queue.pop());
}
public void push(Object obj){
stack1.push(obj);
}
public Object pop() {
if(stack2.isEmpty() && stack1.isEmpty()){// 如果队列为空,则报队列为空的异常
try {
throw new Exception("队列为空");
} catch (Exception e) {
e.printStackTrace();
}
}
if(!stack1.isEmpty()){//stack1不空,说明stack2为空,此时将stack1的数据移除到stack2,只留最后一个用于返回
while(stack1.size() != 1){
stack2.push(stack1.pop());
}
return stack1.remove(0);
}
else{//stack2不空,说明stack1为空,将第一个数据移除并返回,此时将stack2剩下的数据全移除到stack1
Object daishan=stack2.pop();
while(stack2.size() != 0){
stack1.push(stack2.pop());
}
return daishan;
}
}
}
第二部分 队列实现栈
代码
public class StackTest {
/**
两个队列实现栈,把数据放到一个队列中queue,
每次pop时将queue的值给queue1,
下次pop将数据移除到另一个队列,以此类推
**/
static Queue queue = new LinkedList();
static Queue queue1 = new LinkedList();
public static void main(String[] args) throws Exception {
// 队列先进先出、栈先进后出
//放数据
StackTest stack = new StackTest();
stack.offer("aaa");
stack.offer("bbb");
stack.offer("ddd");
stack.offer("eee");
stack.offer("fff");
System.out.println(pop());
System.out.println(pop());
}
public void offer(Object obj){
queue.offer(obj);
}
public static Object pop() throws Exception {
if(queue.isEmpty()&& queue1.isEmpty()){
throw new Exception("栈为空.............");
}
if(!queue.isEmpty()){
ToAnother();//将数据移除到另一个队列中
return queue.remove();
}
if(!queue1.isEmpty()){
ToAnother();
return queue1.remove();
}
else{
return -1;
}
}
public static void ToAnother(){
if(queue.isEmpty()){// queue是空
while(queue1.size()!=1){
queue.offer(queue1.poll());
}
}else if(queue1.isEmpty()){
while(queue.size()!=1){
queue1.offer(queue.poll());
}
}
}
}