public Integer poll(){ Integer re=null; if(!stack2.empty()){ re=stack2.pop(); }else{ while(!stack1.empty()){//move to stack2 to make stack1 have only one element.Then pop this element. re=stack1.pop(); stack2.push(re); } if(!stack2.empty()){ re=stack2.pop(); } } return re; } public Integer offer(int o){ stack1.push(o); return o; }
/* * Q 57 用两个队列实现一个栈 */ public class StackImplementByTwoQueues {
//use 'queue1' and 'queue2' as a queue.That means only use the method 'addLast' and 'removeFirst'. private LinkedList<Integer> queue1; private LinkedList<Integer> queue2;
public Integer pop(){ Integer re=null; if(queue1.size()==0&&queue2.size()==0){ return null; } if(queue2.size()==0){ while(queue1.size()>0){ re=queue1.removeFirst(); if(queue1.size()!=0){//do not add the last element of queue1 to queue2 queue2.addLast(re); } } }else if (queue1.size()==0){ while(queue2.size()>0){ re=queue2.removeFirst(); if(queue2.size()!=0){//do not add the last element of queue2 to queue1 queue1.addLast(re); } } } return re; } public Integer push(Integer o){ if(queue1.size()==0&&queue2.size()==0){ queue1.addLast(o);//queue2.addLast(o); is also ok } if(queue1.size()!=0){ queue1.addLast(o); }else if(queue2.size()!=0){ queue2.addLast(o); } return o; }