队列实现栈

232 阅读1分钟
import java.util.LinkedList;
import java.util.Queue;
public class Queen_To_Stack {
    public class QueenStack{
        private Queue<Integer> data;
        private Queue<Integer> help;
        public QueenStack(){
            data = new LinkedList<Integer>();
            help = new LinkedList<Integer>();
        }
        public void push(int newNum){
            data.add(newNum);
        }
        public int peek(){
            if(data.isEmpty()){
                throw new RuntimeException("stack is empty");
            }
            while(data.size() != 1){
                help.add(data.poll());
            }
            int res = data.poll();
            help.add(res);
            swap();
            return res;
        }
        public int poll(){
            if(data.isEmpty()){
                throw new RuntimeException("stack is empty");
            }
            while(data.size() > 1){
                help.add(data.poll());
            }
            int res = data.poll();
            swap();
            return res;
        }
        public void swap(){
            Queue<Integer> temp = data;
            data = help;
            help = temp;
        }
    }
}