每天一道算法題——用兩個棧實現隊列和用兩個隊列實現棧

1.用兩個棧實現隊列

題目描述

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

測試用例:

[“PSH1”,”PSH2”,”PSH3”,”POP”,”POP”,”PSH4”,”POP”,”PSH5”,”POP”,”POP”]

對應輸出應該爲:

1,2,3,4,5

源碼:

import java.util.Stack;

public class Test1 {
    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.isEmpty()) {
            while(!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}

運行時間
16ms

2.用兩個隊列實現棧

題目描述

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

分析:
入棧:將元素進隊列q1
出棧:判斷隊列q1中元素的個數是否爲1,如果等於1,則出隊列,否則將隊列q1中的元素 以此出隊列並放入隊列q2,直到隊列q1中的元素留下一個,然後隊列q1出隊列,再把 隊列q2中的元素出隊列以此放入隊列q1中。
也就是說把非空隊列的n-1個壓人空對列,剩的第n個出隊…即總有一個隊列爲空。

import java.util.ArrayDeque;
import java.util.Queue;

public class Test1 {

    Queue<Integer> q1 = new ArrayDeque<Integer>();
    Queue<Integer> q2 = new ArrayDeque<Integer>();

    public void push(int node) {
        if(q1.isEmpty()){
            q2.offer(node);
        }else{
        q1.offer(node);
        }
    }

    public int pop() {
        if (q2.isEmpty()&&!q1.isEmpty()) {
            return swapQueue(q2, q1);
        }else if (q1.isEmpty()&&!q2.isEmpty()) {
            return swapQueue(q1, q2);
        }
        return -1;
    }
    private int swapQueue(Queue<Integer> q1,Queue<Integer> q2) {
        while(q2.size()!=1){
            q1.offer(q2.poll());
        }
        return q2.poll();
    }
}

此處有一個易錯點

public class TestMain {
    public static void main(String[] args) {
        Test1 test1 = new Test1();
        test1.push(1);
        test1.push(2);
        test1.push(3);
        test1.push(4);
        test1.push(5);
        Integer i = null;  //注意此處設置一個額外的變量,是因爲如果直接
        // System.out.println(test1.pop())的話,會再進行一次出棧的操作的。

        while ( (i = test1.pop()) != -1){  
            System.out.println(i);
        }       
    }
}

另外,此處可以將方法pop()的返回值改爲Integer,這樣可以直接return null。就避免了存儲-1的尷尬情景了。
即:

public Integer pop() {
        if (q2.isEmpty()&&!q1.isEmpty()) {
            return swapQueue(q2, q1);
        }else if (q1.isEmpty()&&!q2.isEmpty()) {
            return swapQueue(q1, q2);
        }
        return null;
    }

運行時間:
6ms

發佈了45 篇原創文章 · 獲贊 8 · 訪問量 9912
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章