【算法】使用數(shù)組實(shí)現(xiàn)隊(duì)列

眾所周知,隊(duì)列是一種先進(jìn)先出(First-in-first-out 簡(jiǎn)稱FIFO)數(shù)據(jù)結(jié)構(gòu)甚疟。

為了實(shí)現(xiàn)隊(duì)列茧跋,我們??可以使用動(dòng)態(tài)數(shù)組和指向隊(duì)列頭部的索引。

如上所述悲幅,隊(duì)列應(yīng)該支持兩個(gè)操作:enqueue和dequeue套鹅。Enqueue會(huì)向隊(duì)列追加一個(gè)新元素,而dequeue會(huì)刪除第一個(gè)元素汰具。所以我們需要一個(gè)索引來指出起點(diǎn)卓鹿。

代碼如下:

class MyCircularQueue {
       final int[] a;
        int front, rear = -1, len = 0;

        public MyCircularQueue(int k) { a = new int[k];}

        public boolean enQueue(int val) {
            if (!isFull()) {
                rear = (rear + 1) % a.length;
                a[rear] = val;
                len++;
                return true;
            } else return false;
        }

        public boolean deQueue() {
            if (!isEmpty()) {
                front = (front + 1) % a.length;
                len--;
                return true;
            } else return false;
        } 

        public int Front() { return isEmpty() ? -1 : a[front];}

        public int Rear() {return isEmpty() ? -1 : a[rear];}

        public boolean isEmpty() { return len == 0;}

        public boolean isFull() { return len == a.length;}

}

上面的代碼有個(gè)問題就是,隨著p_start 增加留荔,空間的浪費(fèi)吟孙。對(duì)此,我們進(jìn)行優(yōu)化,使用循環(huán)的隊(duì)列(Circular Queue)代碼如下:

class MyCircularQueue {
    
    private int[] data;
    private int head;
    private int tail;
    private int size;

    /** Initialize your data structure here. Set the size of the queue to be k. */
    public MyCircularQueue(int k) {
        data = new int[k];
        head = -1;
        tail = -1;
        size = k;
    }
    
    /** Insert an element into the circular queue. Return true if the operation is successful. */
    public boolean enQueue(int value) {
        if (isFull() == true) {
            return false;
        }
        if (isEmpty() == true) {
            head = 0;
        }
        tail = (tail + 1) % size;
        data[tail] = value;
        return true;
    }
    
    /** Delete an element from the circular queue. Return true if the operation is successful. */
    public boolean deQueue() {
        if (isEmpty() == true) {
            return false;
        }
        if (head == tail) {
            head = -1;
            tail = -1;
            return true;
        }
        head = (head + 1) % size;
        return true;
    }
    
    /** Get the front item from the queue. */
    public int Front() {
        if (isEmpty() == true) {
            return -1;
        }
        return data[head];
    }
    
    /** Get the last item from the queue. */
    public int Rear() {
        if (isEmpty() == true) {
            return -1;
        }
        return data[tail];
    }
    
    /** Checks whether the circular queue is empty or not. */
    public boolean isEmpty() {
        return head == -1;
    }
    
    /** Checks whether the circular queue is full or not. */
    public boolean isFull() {
        return ((tail + 1) % size) == head;
    }
}

/**
 * Your MyCircularQueue object will be instantiated and called as such:
 * MyCircularQueue obj = new MyCircularQueue(k);
 * boolean param_1 = obj.enQueue(value);
 * boolean param_2 = obj.deQueue();
 * int param_3 = obj.Front();
 * int param_4 = obj.Rear();
 * boolean param_5 = obj.isEmpty();
 * boolean param_6 = obj.isFull();
 */

原理就是:使用固定大小的數(shù)組(a fixed-size array)和兩個(gè)變量(two pointers)-head 指示起始位置和 tail 指示結(jié)束位置杰妓,初始化時(shí)head 和tail 均為-1肥隆,入隊(duì)(enQueue)的時(shí)候(tail+1)% fixed-size,出隊(duì)(deQueue)的時(shí)候(head+1)% fixed-size,head == 1時(shí)候隊(duì)列為空,((tail + 1) % size) == head時(shí)候隊(duì)列滿了稚失。

很多高級(jí)語言栋艳,都有內(nèi)置的隊(duì)列庫(kù),所以我們不需要重復(fù)造輪子(reinvent the whell),比如Java

// "static void main" must be defined in a public class.
public class Main {
    public static void main(String[] args) {
        // 1. Initialize a queue.
        Queue<Integer> q = new LinkedList();
        // 2. Get the first element - return null if queue is empty.
        System.out.println("The first element is: " + q.peek());
        // 3. Push new element.
        q.offer(5);
        q.offer(13);
        q.offer(8);
        q.offer(6);
        // 4. Pop an element.
        q.poll();
        // 5. Get the first element.
        System.out.println("The first element is: " + q.peek());
        // 7. Get the size of the queue.
        System.out.println("The size is: " + q.size());
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末句各,一起剝皮案震驚了整個(gè)濱河市吸占,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌凿宾,老刑警劉巖矾屯,帶你破解...
    沈念sama閱讀 219,188評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異初厚,居然都是意外死亡件蚕,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門产禾,熙熙樓的掌柜王于貴愁眉苦臉地迎上來排作,“玉大人,你說我怎么就攤上這事亚情⊥荆” “怎么了?”我有些...
    開封第一講書人閱讀 165,562評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵楞件,是天一觀的道長(zhǎng)衫生。 經(jīng)常有香客問我,道長(zhǎng)土浸,這世上最難降的妖魔是什么罪针? 我笑而不...
    開封第一講書人閱讀 58,893評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮黄伊,結(jié)果婚禮上泪酱,老公的妹妹穿的比我還像新娘。我一直安慰自己毅舆,他們只是感情好西篓,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,917評(píng)論 6 392
  • 文/花漫 我一把揭開白布愈腾。 她就那樣靜靜地躺著憋活,像睡著了一般。 火紅的嫁衣襯著肌膚如雪虱黄。 梳的紋絲不亂的頭發(fā)上悦即,一...
    開封第一講書人閱讀 51,708評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼辜梳。 笑死粱甫,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的作瞄。 我是一名探鬼主播茶宵,決...
    沈念sama閱讀 40,430評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼宗挥!你這毒婦竟也來了乌庶?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,342評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤契耿,失蹤者是張志新(化名)和其女友劉穎瞒大,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體搪桂,經(jīng)...
    沈念sama閱讀 45,801評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡透敌,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,976評(píng)論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了踢械。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片酗电。...
    茶點(diǎn)故事閱讀 40,115評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖内列,靈堂內(nèi)的尸體忽然破棺而出顾瞻,到底是詐尸還是另有隱情,我是刑警寧澤德绿,帶...
    沈念sama閱讀 35,804評(píng)論 5 346
  • 正文 年R本政府宣布荷荤,位于F島的核電站,受9級(jí)特大地震影響移稳,放射性物質(zhì)發(fā)生泄漏蕴纳。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,458評(píng)論 3 331
  • 文/蒙蒙 一个粱、第九天 我趴在偏房一處隱蔽的房頂上張望古毛。 院中可真熱鬧,春花似錦都许、人聲如沸稻薇。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,008評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽塞椎。三九已至,卻和暖如春睛低,著一層夾襖步出監(jiān)牢的瞬間案狠,已是汗流浹背服傍。 一陣腳步聲響...
    開封第一講書人閱讀 33,135評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留骂铁,地道東北人吹零。 一個(gè)月前我還...
    沈念sama閱讀 48,365評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像拉庵,于是被迫代替她去往敵國(guó)和親灿椅。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,055評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容