算法第二週作業03

Description

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

Solutions

入隊時,直接向其中一個棧(假設stack1)進行入棧操作;

出隊時,將stack1的除了最裏面的數據,全部依次出棧併入棧stack2,然後stack1剩餘的一個元素就是出隊結果,把它出棧並保存爲臨時變量,用於返回;然後將stack2的數據全部出棧併入棧stack1.

Code

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() {
    	while(stack1.size() != 1){
            stack2.push(stack1.pop());
        }
        int result = stack1.pop();
        while(!stack2.isEmpty()){
            stack1.push(stack2.pop());
        }
        return result;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章