leetcode [Implement Stack using Queues]//待整理多种解法

来源:互联网 发布:双代号网络计划 编辑:程序博客网 时间:2024/04/29 12:28
public class MyStack {    //题目中提到You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).//所以不用考虑鲁棒性,但是实际编程应该注意鲁棒性Queue<Integer> queue = null;//用队列实现一个栈/** Initialize your data structure here. */public MyStack() {queue = new LinkedList<Integer>();}/** Push element x onto stack. */public void push(int x) {//因为是用队列实现一个栈,所以每次压入元素时把队列里的元素先取出来,压入元素后再把取出的压进去int[] out = new int[queue.size()];for(int i = 0; i < out.length; i++){//取出队列里已有的元素out[i] = queue.poll();}queue.add(x);//压入x元素for(int temp : out){queue.add(temp);//再压入取出的元素,这样能保证后进先出的顺序}}/** Removes the element on top of the stack and returns that element. */public int pop() {return queue.poll();}/** Get the top element. */public int top() {return queue.peek();}/** Returns whether the stack is empty. */public boolean empty() {return queue.isEmpty();}}/** * Your MyStack object will be instantiated and called as such: * MyStack obj = new MyStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * boolean param_4 = obj.empty(); */

0 0
原创粉丝点击