栈和队列
https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/solution/
(用两个栈实现队列)
class CQueue { LinkedList<Integer> stack1; LinkedList<Integer> stack2; public CQueue() { stack1 = new LinkedList<>(); stack2 = new LinkedList<>(); } public void appendTail(int value) { stack1.add(value); } public int deleteHead() { if (stack2.isEmpty()) { if (stack1.isEmpty()) return -1; while(!stack1.isEmpty()) { stack2.add(stack1.pop()); } return stack2.pop(); }else return stack2.pop(); } } /** * Your CQueue object will be instantiated and called as such: * CQueue obj = new CQueue(); * obj.appendTail(value); * int param_2 = obj.deleteHead(); */
https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/(维护一个最小栈)
class MinStack { /** initialize your data structure here. */ LinkedList<Integer> stack1; LinkedList<Integer> stack2; public MinStack() { stack1 = new LinkedList<>(); stack2 = new LinkedList<>(); } public void push(int x) { stack1.addLast(x); if (stack2.isEmpty() || x <= stack2.peekLast()) { stack2.addLast(x); } } public void pop() { if(stack1.pollLast().equals(stack2.peekLast())) stack2.pollLast(); } public int top() { return stack1.peekLast(); } public int min() { return stack2.peekLast(); } } /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.min(); */