Queue structure and implementation

queue definition

Queue refers to a data structure, which is characterized by FIFO (First In First Out), that is, first in first out.

The data of the queue can only be deleted at the end, so the queue can be regarded as a queue, a group of people line up to check out, and whoever queues first will check out first.

Implementation of the queue

The insertion and deletion of data in the queue can only be performed by tail insertion and head deletion. Considering the low efficiency of sequence table head deletion, a linked list is selected to implement the queue. Although the tail insertion efficiency of the linked list is low, a tail pointer can be used to improve the tail insertion efficiency.

Queue implementation:

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

typedef int QueueDataType;

typedef struct QueueNode {
    QueueDataType data;
    struct QueueNode* next;
}QueueNode;

//头指针和尾指针可以写成变量,但是函数传参时会很麻烦,可以写成一个结构体:
typedef struct Queue {
    QueueNode* first;
    QueueNode* tail;
}Queue;

void QueueInit(Queue* p){
    assert(p);
    p->first = p->tail = NULL;
}

bool QueueEmpty(Queue* p){
    assert(p);
    return p->first == NULL;
}

void QueueDestory(Queue* p){
    assert(p);
    QueueNode* cur = p->first;
    QueueNode* next = NULL;
    while(cur){
        next = cur->next
        free(cur);
        cur = next;
    }
}

void QueuePush(Queue* p, QueueDataType x){
    assert(p);
    QueueNode* new = (QueueNode*)malloc(sizeof(QueueNode));
    if(tem == NULL){
        perror("malloc fail");
        return;
    }
    nem->data = x;
    nem->next = NULL;
    //尾插分两种情况:队列为空或不为空
    if(QueueEmpty){
        p->first = p->tail = new;
    }
    else{
        p->tail->next = new;
        p->tail = new;
    }
}

void QueuePop(Queue* p){
    assert(p);
    //数据删除,队列不能为空
    assert(!QueueEmpty(p));
    //头删分两种情况:
    if(p->first == p->tail){
    //队列中只有一个元素
        free(p->first);
        p->first = p->tail = NULL;
    }
    else{
    //队列中有多个元素
        QueueNode* next = p->first->next;
        free(p->first);
        p->first = next;
    }
}

void QueueFront(Queue* p){
    assert(p);
    assert(!QueueEmpty(p));
    return p->first->data;
}

void QueueTail(Queue* p){
    assert(p);
    assert(!QueueEmpty(p));
    return p->tail->data;
}

Guess you like

Origin blog.csdn.net/weixin_74269833/article/details/129690753