双端队列C实现代码 算法导论10.1-5 10.1-6 10.1-7

数组实现双端队列的时候注意区别判断上溢和下溢。

用两个栈实现队列,就相当于把两个栈底靠在一起(背靠背),一个栈用来出队列,一个栈用来进队列。这个队列的操作时间大部分时候是常数时间,除了出列的栈为空,需要把进列的栈全部转移过去,再出列。Back()操作和Pop()操作类似,也是这样。

而两个队列实现栈,队列轮流充当入栈和出栈的角色,而什么时候会改变角色呢,就是Pop()操作。Pop()操作先把一个队列中的所有元素全部出列并加入另外一个空队列中去,然后再出列(第二个队列)。

实现代码为C

#include <stdio.h>
#include <stdlib.h>

#define Max 100

//双端队列实现c
typedef 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);
}
原文地址:https://www.cnblogs.com/Nastukashii/p/4418303.html