0
点赞
收藏
分享

微信扫一扫

03.数据结构之队列

陆公子521 2022-04-06 阅读 60
数据结构

队列的定义

typedef struct Queue {
    int* data;
    int lengeth;
    int head, tail, length;
}Queue;

获取队头元素

int front(Queue* q) {
    return q->data[q->head];
}

队列的初始化

Queue* init(int n) {
    Queue* q = (Queue*)malloc(sizeof(Queue));
    q->data = (int*)malloc(sizeof(int) * n);
    q->lengeth = n;
    q->head = q->tail = 0;
    return q;
}

队列的清空操作

void clear(Queue* q) {
    if (q == NULL) return;
    free(q->data);
    free(q);
}

队尾添加元素操作

int push(Queue* q, int val) {
    if (q == NULL) return 0;
    if (q->tail == q->length) return 0;
    q->data[q->tail++] = val;
    return 1;
}

队列判空操作

int empty(Queue* q) {
    return q->head == q->tail;
}

移除队头元素操作

int pop(Queue* q) {
    if (q == NULL) return 0;
    if (empty(q)) return 0;
    q->head++;
    return 1;
}

打印操作

void output(Queue* q) {
    printf("[");
    for (int i = q->head; i < q->tail; i++) {
        i != q->head && printf(" ");
        printf("%d", q->data[i]);
    }
    printf("]\n");
    return;
}

主函数测试用例

int main()
{
    srand(time(0));
	#define MAX_OP 20
    Queue* q = init(MAX_OP);

    for (int i = 0; i < MAX_OP; i++) {
        int op=rand()%4;
        int val = rand() % 100;
        switch (op) {
        case 0: 
        case 1:
        case 2:
        {
            printf("push %d to Queue = %d\n", val, push(q, val));
            
        }break;
        case 3: {
            if (empty(q)) {
                printf("fail to pop a item !\n");
            }
            else {
                //程序是从右往左运行的,顺序不能错
                printf("success to :%d  pop a item  %d\n", pop(q),front(q));
            }
        }break;
        }
        output(q), printf("\n");

    }
	#undef MAX_OP
    clear(q);
    return 0;
}
举报

相关推荐

0 条评论