雙端隊列C實現代碼 演算法導論10.1-5 10.1-6 10.1-7

來源:互聯網
上載者:User

標籤:

數組實現雙端隊列的時候注意區別判斷上溢和下溢。

用兩個棧實現隊列,就相當於把兩個棧底靠在一起(背靠背),一個棧用來出隊列,一個棧用來進隊列。這個隊列的操作時間大部分時候是常數時間,除了出列的棧為空白,需要把進列的棧全部轉移過去,再出列。Back()操作和Pop()操作類似,也是這樣。

而兩個隊列實現棧,隊列輪流充當入棧和出棧的角色,而什麼時候會改變角色呢,就是Pop()操作。Pop()操作先把一個隊列中的所有元素全部出列並加入另外一個空隊列中去,然後再出列(第二個隊列)。

實現代碼為C

#include <stdio.h>#include <stdlib.h>#define Max 100//雙端隊列實現ctypedef struct{    int head;    int tail;    int a[Max];}Deque;void Init_Deque(Deque *d){    d->head = -1;    d->tail = 0;}bool Empty(Deque *d){    return d->head == -1;}void Push_Back(Deque *d,int key){    if (d->head == d->tail){        fprintf(stderr, "Deque overflow");        exit(1);    }    if (d->head == -1)        d->head = d->tail;    d->a[d->tail] = key;    d->tail = (d->tail + 1) % Max;}int Pop_Back(Deque *d){    if (d->head == -1){        fprintf(stderr, "Deque underflow");        exit(1);    }    d->tail = (d->tail - 1+Max) % Max;    if (d->head == d->tail)        d->head = -1;    return d->a[d->tail];}void Push_Front(Deque *d,int key){    if (d->head == d->tail){        fprintf(stderr, "Deque overflow");        exit(1);    }    if (d->head == -1)        d->head = d->tail;    d->head = (d->head - 1 + Max) % Max;    d->head = key;}int Pop_Front(Deque *d){    if (d->head == -1){        fprintf(stderr, "Deque underflow");        exit(1);    }    int temp = d->a[d->head];    d->head = (d->head + 1) % Max;    if (d->head == d->tail)        d->head = -1;    return temp;}//兩個棧實現一個隊列typedef struct{    Deque inqueue;    Deque dequeue;}Like_Queue;void Push(Like_Queue *lq,int key){    Push_Back(&lq->inqueue, key);}int Pop(Like_Queue *lq){    if (Empty(&lq->dequeue)){        while (!Empty(&lq->inqueue)){            int temp = Pop_Back(&lq->inqueue);            Push_Back(&lq->dequeue, temp);        }    }    return Pop_Back(&lq->dequeue);}

 

雙端隊列C實現代碼 演算法導論10.1-5 10.1-6 10.1-7

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.