C语言---队列(链表实现)

队列的基本概念
队列 (Queue) :也是运算受限的线性表。是一种先进先出 (First In First Out ,简称 FIFO) 的线性表。只允许在表的一端进行插入,而在另一端进行删除。
队首 (front) :允许进行删除的一端称为队首。
队尾 (rear) :允许进行插入的一端称为队尾。

#include<stdio.h>
#include<stdlib.h>
#define ElementType int
#define ERROR -99

//构建结点信息 
typedef struct Node{
    ElementType data;
    struct Node *next;
}QNode;
//构建节点头和尾指针,在队列的的增加和删除操作分别在尾和头部执行
 
typedef struct {
    QNode *front;
    QNode *rear;
}Queue;

Queue* CreateQueue(){
//申请结点内存,成功返回大于零的值,否则返回NULL 
    Queue* q = (Queue *)malloc(sizeof(Queue));
    if(!q){
        printf("内存空间不足\n");
        return NULL;
    }
//指针初值为NULL 
    q->front = q->rear = NULL;
    return q;
}

void AddQ(Queue *q,ElementType item){
    QNode* qNode=(QNode*)malloc(sizeof(QNode));
    if(!qNode){
        printf("内存空间不足\n");
        exit(-1);
    }
    qNode->data = item;
    qNode->next = NULL;
    if(q->front==NULL){
        q->front = qNode;
    }
    if(q->rear == NULL){
        q->rear = qNode;
    }
    else{
//头尾不为null,则执行下列操作
//连上上一个指针 
        q->rear->next=qNode;
//队尾指针从新被定义 
        q->rear=qNode;
    }
}

int IsEmptyQ(Queue* q){
    return (q->front == NULL);
}

ElementType DeleteQ(Queue* q){
    int item;
    if(IsEmptyQ(q)){
        printf("空队列\n");
        return ERROR;
    }
    QNode *temp = q->front;
    if(q->rear == q->front){
        q->rear=NULL;
        q->front=NULL;
    }
    else{
//在队列头指针进行操作 
        q->front = q->front->next;
    }
    item = temp->data;
    free(temp);
    return item;
}

void PrientQueue(Queue *q){
    if(IsEmptyQ(q)){
        printf("空队列\n");
        return ;
    }
    printf("打印队列所有元素:\n");
    QNode *qnode = q->front;
    while(qnode != NULL){
        printf("%d",qnode->data);
        qnode= qnode->next;
    }
    printf("\n");
}

int main(){
    Queue *q = CreateQueue();
    AddQ(q,1);
    AddQ(q,2);
    AddQ(q,3);
    AddQ(q,4);
    PrientQueue(q);
    
    DeleteQ(q);
    DeleteQ(q);
    PrientQueue(q);
    
    return 0;
}

运行结果图

猜你喜欢

转载自www.cnblogs.com/changfan/p/11737466.html