0
点赞
收藏
分享

微信扫一扫

链表实现队列

#include "cstdio"
#define max_size 16


typedef struct QNode{
    int data;
    struct QNode *next;
}QNode;


typedef QNode *QueuePtr;


typedef struct Queue{
//    队列长度
    int length;
//    队列头指针
    QueuePtr front;
//或者这么写
//    QNode *front;

//    尾指针
    QueuePtr rear;
}LinkQueue;


void InitQueue(LinkQueue *LQ){
    if(!LQ) return;
    LQ->length = 0;
    LQ->front = LQ->rear = NULL;
}


int IsEmpty(LinkQueue *LQ){
    if(!LQ) return 0;
    if(LQ->front == NULL){
        return 1;
    }
    return 0;
}


int IsFull(LinkQueue *LQ){
    if(!LQ) return 0;
    if(LQ->length == max_size){
        return 1;
    }
    return 0;
}


int InsertQueue(LinkQueue *LQ, int value){
    if(!LQ) return 0;
    if(IsFull(LQ)){
        printf("队列已满,无法插入\n");
        return 0;
    }
    QNode *q = new QNode;
    q->data = value;
    q->next = NULL;
//    空队列
    if(IsEmpty(LQ)){
        LQ->front = LQ->rear = q;
    }else{
//        队尾插入节点
        LQ->rear->next = q;
//        队尾指向插入的节点
        LQ->rear = q;
    }
    LQ->length++;
    return 1;
}


int DeleteQueue(LinkQueue *LQ, int *value){
    QNode *temp = NULL;
    if(!LQ || IsEmpty(LQ)){
        printf("队列为空,无法删除\n");
        return 0;
    }
    if(!value){
        return 0;
    }
    temp = LQ->front;
    LQ->front = temp->next;
//    队首出列的情况,队尾置空
    if(!LQ->front){LQ->rear = NULL;}
    *value = temp->data;
    LQ->length--;
    delete temp;
    return 1;
}


void DisplayQueue(LinkQueue *LQ){
    QueuePtr temp;
    if(!LQ)return;
    temp = LQ->front;
    while (temp){
        printf("%d ,", temp->data);
        temp = temp->next;
    }
    printf("\n");
}


int GetHead(LinkQueue *LQ, int *value){
    if(!LQ || IsEmpty(LQ)){
        printf("队列为空\n");
        return 0;
    }
    if(!value)return 0;
    *value = LQ->front->data;
    return 1;
}


void ClearQueue(LinkQueue *LQ){
    if(!LQ)return;
    while (LQ->front){
        QueuePtr temp = LQ->front->next;
        delete LQ->front;
        LQ->front = temp;
    }
    LQ->front = LQ->rear = NULL;
    LQ->length = 0;
}


int GetLength(LinkQueue *LQ){
    if(!LQ)return 0;
    return LQ->length;
}


int main(){
    LinkQueue *LQ = new LinkQueue ;
    InitQueue(LQ);
    for(int i = 0; i < 6; i++){
        InsertQueue(LQ, i + 1);
    }
    printf("队列长度为%d\n", GetLength(LQ));
    DisplayQueue(LQ);
    int value = -1;
    DeleteQueue(LQ, &value);
    DisplayQueue(LQ);
    ClearQueue(LQ);
    DisplayQueue(LQ);
    return 0;
}

链表实现队列_#define

举报

相关推荐

0 条评论