非常簡單的代碼實現棧和隊列

一,棧

我們直到 棧的特點是先進後出,我們基於數組形式寫一個簡單的棧便於你們理解

下邊是代碼 直接輔助測試就可以 裏邊有測試結果

package com.jxd.test;

public class JxdStack {

    private String item[];//數組用於存放數據
    private int length;//數組的長度
    private int count;//數據的個數
    public JxdStack(int n) {
        item = new String[n];
        this.length = n;
        this.count = 0;
    }

    /**
     * 出棧
     */
    public String pop() {
        if(count==0) return null;//表述數組裏變沒有數據了
        String str =item[count-1];
        count--;
        return str;
    }

    /**
     * 入棧
     */
    public boolean push(String str) {
        if (count ==length) return false;//表示數據滿了
        item[count++] = str;
        return true;
    }

    public static void main(String[] args) {
        JxdStack jxdStack =  new JxdStack(3);
        for(int i =0;i<2;i++){//入棧
            jxdStack.push("jxd"+i);
        }
       
        for(int i =0;i<3;i++){//出棧操作
            System.out.println(jxdStack.pop());
        }
    }
}

 

二,隊列

隊列的特點是,先進先出,後進後出同樣我們基於數組形式寫一個簡單的隊列,以下是代碼非常詳細

自己可以直接複製跑一下,測似一下

package com.jxd.test;

public class JxdQueue {
    private String item[];//存放隊列的數據
    private int length;//隊列的長度
    private int count;//隊列中的個數
    private int prve;//前指針爲了滿足先進先出

    public JxdQueue(int n) {
        item = new String[n];
        this.length = n;
        this.count = 0;
        this.prve = 0;
    }

    /**
     * 入隊
     */
    public boolean enqueue(String str) {
        if (count == length) {
            //如果count == length且 prve == 0表示數據存滿了 直接返回fasle
            if (prve == 0) return false;
            /**
             * 擴容 比如
             * 我們數組這樣{a,b,c,d,e,f}
             * 當我們prev=2 也就是指針指到c 且 count -1指針指到f的情況下
             * 我們把d, e,f 整體向前移動且覆蓋 變成{d,e,f,d,e,f}
             * 我們把指針變動一下 prev =0, count指針指向count-prve即 下標爲2處
             * 這樣把下標3,4,5的數據修改爲null 我們這裏沒有這麼操作 你記住就可以
             * 這樣就騰出空來了 以便以後裝數據
             */
            for (int i = prve; i < length; i++) {
                item[i - prve] = item[i];
            }
            count=count-prve;
            prve=0;
        }

        item[count++] = str;
        return true;
    }

    /**
     * 出隊
     */
    public String dequeue() {
        if (prve == length) return null;//表示指針已經到最後一個沒有數據要取了
        String str = item[prve++];
        return str;
    }

    public static void main(String[] args) {
        JxdQueue jxdQueue = new JxdQueue(5);
        //先存五個數據
        for (int i = 0; i < 5; i++) {
            jxdQueue.enqueue("jxd" + i);
        }
        //再取2個數據
        for (int i = 0; i < 2; i++) {
            System.out.println(jxdQueue.dequeue());
        }
        
        //然後再存2個新數據
        for (int i = 0; i < 2; i++) {
            jxdQueue.enqueue("wudi" + i);
        }
        //然後遍歷一下整個隊列情況
        for (int i = 0; i < 5; i++) {
            System.out.println(jxdQueue.dequeue());
        }
    }
}

 

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