1. 程式人生 > >用兩個棧實現佇列 劍指offer java

用兩個棧實現佇列 劍指offer java

題目描述

用兩個棧來實現一個佇列,完成佇列的Push和Pop操作。 佇列中的元素為int型別。

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack1.push(node);
    }
    
    public int pop() {
    if(stack2.size()==0){
        while(!stack1.empty()){
            stack2.push(stack1.pop());
    }
    }
        if (stack2.size() == 0) {//當stack1和stack2都長度為0的時候,執行到這裡還是會出現stack2的長度為0,所以要做異常處理
            System.out.println("stack1和stack2的長度都為0,不能進行pop操作,丟擲異常");
            return -1;
        }
      return stack2.pop();
    }
        
}

測試案例:

import java.util.Stack;

public class QueuesToStack
{
        Stack<Integer> stack1 = new Stack<Integer>();
        Stack<Integer> stack2 = new Stack<Integer>();

        public void push(int node) {
            stack1.push(node);
        }

        public int pop() {
            if(stack2.size()==0){
                while(!stack1.empty()){
                    stack2.push(stack1.pop());
                }
            }
            if (stack2.size() == 0) {//當stack1和stack2都長度為0的時候,執行到這裡還是會出現stack2的長度為0,所以要做異常處理
                System.out.println("stack1和stack2的長度都為0,不能進行pop操作,丟擲異常");
                return -1;
            }
            return stack2.pop();
        }

    public static void main(String[] args)
    {
        QueuesToStack stack=new QueuesToStack();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        stack.push(5);
        stack.push(6);
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
    }
}

輸出:

1
2
3
4
5
6
stack1和stack2的長度都為0,不能進行pop操作,丟擲異常
-1