Queue<Integer> q; /** Initialize your data structure here. */ public MyStack() { q = new LinkedList<>(); } /** Push element x onto stack. */ public void push(int x) { q.offer(x); for (int i = 1; i < q.size(); ++i) { q.offer(q.poll()); } } /** Removes the element on top of the stack and returns that element. */ public int pop() { return q.poll(); } /** Get the top element. */ public int top() { return q.peek(); } /** Returns whether the stack is empty. */ public boolean empty() { return q.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(); */
Stack<Integer> s1; Stack<Integer> s2; /** Initialize your data structure here. */ public MyQueue() { s1 = new Stack<>(); s2 = new Stack<>(); } /** Push element x to the back of queue. */ public void push(int x) { s1.push(x); } /** Removes the element from in front of queue and returns that element. */ public int pop() { peek(); // 作为tmp的s1搬到s2 return s2.pop(); } /** Get the front element. */ // s2非空,就直接是s2最上面的元素 // s2是空,那么先把FIFO的s1元素全部倒过来放进s2, 再从s2 pop public int peek() { if (!s2.empty()) { return s2.peek(); } else { while (!s1.empty()) { s2.push(s1.pop()); } } return s2.peek(); } /** Returns whether the queue is empty. */ public boolean empty() { return s1.empty() && s2.empty(); } }
/** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = new MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * boolean param_4 = obj.empty(); */