顺序队列


#include 

#define MaxSize 10
typedef struct {
    int data[MaxSize];
    // front指向队头元素,rear指向队尾元素的后一个位置
    int front, rear;
} SqQueue;

void InitQueue(SqQueue *q) {
    q->rear=q->front=0;
}

/*
 *
 * 1. front指向队头元素,rear指向队尾元素的后一个位置
 * * 队满条件: (q.rear+1)%MaxSize == q.front
 * * 队空条件: rear == front
 * * 队列元素个数: (rear-front+MaxSize)%MaxSize
 * 2. 结构体中定义变量: int size = 0, 队列当前长度
 * * 插入成功: size++
 * * 删除成功: size--
 * 3. 结构体中定义变量: int tag = 0, 最近进行的是插入(1)/删除(0)
 * * 插入成功: tag = 1
 * * 删除成功: tag = 0
 * 4. front指向队头元素,rear指向队尾元素
 * * 初始化: rear=MaxSize-1, front=0
 */
int EnQueue(SqQueue *q, int e) {
    if ((q->rear+1)%MaxSize == q->front) return -1;
    q->data[q->rear] = e;
    q->rear = (q->rear+1)%MaxSize;
    return 1;
}

int DeQueue(SqQueue *q, int *e) {
    if (q->rear == q->front) return -1;
    *e = q->data[q->front];
    q->front = (q->front+1)%MaxSize;
    return 1;
}

int GetHead(SqQueue *q, int *e) {
    if (q->rear == q->front) return -1;
    *e = q->data[q->front];
    return 1;
}

int Length(SqQueue q) {
    return (q.rear-q.front+MaxSize)%MaxSize;
}

int Empty(SqQueue q) {
    if (q.rear == q.front) return 1;
    else return -1;
}

int main() {
    SqQueue q;
    InitQueue(&q);
    EnQueue(&q, 10);
    EnQueue(&q, 11);
    EnQueue(&q, 12);
    int e = -1;
    DeQueue(&q, &e);
    printf("%i\n", e);
    DeQueue(&q, &e);
    printf("%i\n", e);
    return 0;
}

你可能感兴趣的:(顺序队列)