/** * Your CQueue object will be instantiated and called as such: * CQueue obj = new CQueue(); * obj.appendTail(value); * int param_2 = obj.deleteHead(); */
publicCQueue(){ Stack1 = new Stack<>(); Stack2 = new Stack<>(); } publicvoidappendTail(int value){ Stack1.push(value); } publicintdeleteHead(){ while(Stack1.size()!=0){ Stack2.push(Stack1.pop()); } if(Stack2.size()==0){ return -1; }else{ int result = Stack2.pop(); while(Stack2.size()!=0){ Stack1.push(Stack2.pop()); } return result; } } }
/** * Your CQueue object will be instantiated and called as such: * CQueue obj = new CQueue(); * obj.appendTail(value); * int param_2 = obj.deleteHead(); */
解法3: 标准答案
使用两个链表。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classCQueue{ LinkedList<Integer> A, B; publicCQueue(){ A = new LinkedList<Integer>(); B = new LinkedList<Integer>(); } publicvoidappendTail(int value){ A.addLast(value); } publicintdeleteHead(){ if(!B.isEmpty()) return B.removeLast(); if(A.isEmpty()) return -1; while(!A.isEmpty()) B.addLast(A.removeLast()); return B.removeLast(); } }
/** * Your CQueue object will be instantiated and called as such: * CQueue obj = new CQueue(); * obj.appendTail(value); * int param_2 = obj.deleteHead(); */
时间复杂度明显降低,但是空间复杂度提升了。
二、 剑指offer30. 包含min函数的栈
要求:定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
/** * 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(); */