1.1、題目1

劍指 Offer 09. 用兩個棧實現佇列

1.2、解法

解法如題目所說。定義兩個棧。這裡假設第一個棧為a,第二個棧為b。

實現兩個函式增加尾和刪除頭。

增加即直接push入第一個棧。

刪除函式:通過判斷a是否為空進行迴圈,將已經存入的a的棧頂pop存到b中,以此達到倒置的效果。

再將b的棧頂pop出來即可達到刪除。

此時a棧為空,下次判斷若b棧為空,則輸出-1。

否則則繼續通過b棧輸出棧頂。

1.3、程式碼

  1. class CQueue {
  2. Deque<Integer> a;
  3. Deque<Integer> b;
  4. public CQueue() {
  5. a = new LinkedList<Integer>();
  6. b = new LinkedList<Integer>();
  7. }
  8. public void appendTail(int value) {
  9. a.push(value);
  10. }
  11. public int deleteHead() {
  12. if(b.isEmpty()){
  13. while(!a.isEmpty()){
  14. b.push(a.pop());
  15. }
  16. }
  17. if(b.isEmpty()){
  18. return -1;
  19. }else{
  20. return (int)b.pop();
  21. }
  22. }
  23. }
  24. /**
  25. * Your CQueue object will be instantiated and called as such:
  26. * CQueue obj = new CQueue();
  27. * obj.appendTail(value);
  28. * int param_2 = obj.deleteHead();
  29. */

2.1、題目2

劍指 Offer 30. 包含min函式的棧

2.2、解法

仍是通過兩個棧的方式,第一個棧為d1,第二個棧為d2

d1的push、pop、top不受影響。

至於d2,push時需將d2棧頂元素與目前元素判斷,若大於或者等於,則存進d2

pop時,若d2棧頂元素與d1 pop的元素相同,則共同pop

此時d2的棧頂為最小值。

2.3、程式碼

  1. class MinStack {
  2. Deque<Integer> d1,d2;
  3. /** initialize your data structure here. */
  4. public MinStack() {
  5. d1 = new LinkedList<Integer>();
  6. d2 = new LinkedList<Integer>();
  7. }
  8. public void push(int x) {
  9. d1.push(x);
  10. if(d2.isEmpty()||d2.peek()>=x){
  11. d2.push(x);
  12. }
  13. }
  14. public void pop() {
  15. if(d1.pop().equals(d2.peek())){
  16. d2.pop();
  17. }
  18. }
  19. public int top() {
  20. return (int)d1.peek();
  21. }
  22. public int min() {
  23. return (int)d2.peek();
  24. }
  25. }
  26. /**
  27. * Your MinStack object will be instantiated and called as such:
  28. * MinStack obj = new MinStack();
  29. * obj.push(x);
  30. * obj.pop();
  31. * int param_3 = obj.top();
  32. * int param_4 = obj.min();
  33. */