劍指offer:4. 用兩個棧實現隊列

4. 用兩個棧實現隊列

題目描述

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

思路:1,整體思路是元素先依次進入棧1,再從棧1依次彈出到棧2,然後彈出棧2頂部的元素,整個過程就是一個隊列的先進先出
2,但是在交換元素的時候需要判斷兩個棧的元素情況:
“進隊列時”,隊列中是還還有元素,若有,說明棧2中的元素不爲空,此時就先將棧2的元素倒回到棧1 中,保持在“進隊列狀態”。
“出隊列時”,將棧1的元素全部彈到棧2中,保持在“出隊列狀態”。
所以要做的判斷是,進時,棧2是否爲空,不爲空,則棧2元素倒回到棧1,出時,將棧1元素全部彈到棧2中,直到棧1爲空。

Java實現:

import java.util.Stack;

/**
 * @Classname Queue
 * @Description TODO
 * @Date 2019/6/3 10:06
 * @Created by 超
 */
public class Queue {
    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.isEmpty()) {
            stack2.push(stack1.pop());
        }
        int first = stack2.pop();
        while (! stack2.isEmpty()) {
            stack1.push(stack2.pop());
        }
        return first;
    }

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

    public int pop1() {
        if (stack1.isEmpty() && stack2.isEmpty()) {
            throw new RuntimeException("Queue is Empty!");
        }
        if (stack2.empty()) {
            while (! stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}

不足之處歡迎批評討論!

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