一、232. Implement Queue using Stacks
private Stack<Integer> stack; /** Initialize your data structure here. */ public e232() { stack = new Stack<>(); } /** Push element x to the back of queue. */ public void push(int x) { stack.push(x); } /** Removes the element from in front of queue and returns that element. */ public int pop() { Stack<Integer> tmp = new Stack<>(); while (!stack.isEmpty()) tmp.push(stack.pop()); int result = tmp.pop(); while (!tmp.isEmpty()) stack.push(tmp.pop()); return result; } /** Get the front element. */ public int peek() { Stack<Integer> tmp = new Stack<>(); while (!stack.isEmpty()) tmp.push(stack.pop()); System.out.println(tmp); int result = tmp.peek(); System.out.println(result); while (!tmp.isEmpty()) stack.push(tmp.pop()); return result; } /** Returns whether the queue is empty. */ public boolean empty() { return stack.isEmpty(); }
二、225. Implement Stack using Queues
private Queue<Integer> queue; /** Initialize your data structure here. */ public e225() { queue = new ArrayDeque<>(); } /** Push element x onto stack. */ public void push(int x) { queue.add(x); } /** Removes the element on top of the stack and returns that element. */ public int pop() { Queue<Integer> tmp = new ArrayDeque<>(); while (queue.size() != 1) tmp.add(queue.poll()); int result = queue.peek(); queue = tmp; return result; } /** Get the top element. */ public int top() { Queue<Integer> tmp = new ArrayDeque<>(); while (queue.size() != 1) { tmp.add(queue.poll()); } int result = queue.peek(); tmp.add(result); queue = tmp; return result; } /** Returns whether the stack is empty. */ public boolean empty() { return queue.isEmpty(); }
三、155. Min Stack
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> Returns -3. minStack.pop(); minStack.top(); --> Returns 0. minStack.getMin(); --> Returns -2.
思路:使用两个栈,一个用来存值,另一个用来存在当前值压入栈后的最小值。
private Stack<Integer> stack1 ; private Stack<Integer> stack2 ; private int min; /** initialize your data structure here. */ public MinStack() { stack1 = new Stack<>(); stack2 = new Stack<>(); min = Integer.MAX_VALUE; } public void push(int x) { stack1.push(x); min = Math.min(min, x); stack2.push(min); } public void pop() { stack1.pop(); stack2.pop(); if (stack2.isEmpty()) { min = Integer.MAX_VALUE; } else { min = stack2.peek(); } } public int top() { return stack1.peek(); } public int getMin() { return stack2.peek(); }
四、739. Daily Temperatures
五、