【劍指offer】5.用兩個棧實現隊列

/**
*題目描述:
*用兩個棧來實現一個隊列,完成隊列的Push和Pop操作。 
*隊列中的元素爲int類型。
*/
import java.util.Stack;

//先進先出與先進後出
public class Solution {
    //保存push進入的元素
    Stack<Integer> stack1 = new Stack<Integer>();
    //保存pop將出的元素
    Stack<Integer> stack2 = new Stack<Integer>();

    //如果stack2爲空,則將stack1所有元素轉移到stack2

    //stack1只管進,stack2只管出

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

    public int pop() {

        while(!stack2.isEmpty()){
            return stack2.pop();
        }

        while(!stack1.isEmpty()){
            stack2.push(stack1.pop());
        }

        return stack2.pop();
    }

    public static void main(String[] args) {

        Solution s=new Solution();

        s.push(1);
        s.push(2);
        s.push(3);
        System.out.println(s.pop());
        System.out.println(s.pop());
        s.push(4);
        System.out.println(s.pop());
        s.push(5);
        System.out.println(s.pop());
        System.out.println(s.pop());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章