队列

<span style="font-size:18px;">#include <stdio.h>
#include <stdlib.h>
struct QNode{
    int data;
    struct QNode* next;
};
struct Queue{
    struct QNode* front;
    struct QNode* rear;
};
 
struct Queue* init();
void destroy(struct Queue ** pq);
int EnQ(struct Queue* q, int item);
int DeQ(struct Queue* q, int *pitem);
 
 
struct Queue* init(){
    struct Queue* tmp;
    tmp = (struct Queue*)malloc(sizeof(struct Queue));
    if(!tmp) return NULL;
    tmp->front = tmp->rear = NULL;
    return tmp;
}
void destroy(struct Queue ** pq){
    if (*pq == NULL)return;
    struct QNode *tmp, *head;
    head = (*pq)->front;
    while (head) {
        tmp = head;
        head = head->next;
        free(tmp);
    }
    free(*pq);
}
int EnQ(struct Queue* q, int item){
    struct QNode* tmp;
    tmp = (struct QNode*)malloc(sizeof(struct QNode));
    if (!tmp) return 0;
    tmp->data = item;
    tmp->next = NULL;
    if (q->front) {
        q->rear->next = tmp;
        q->rear = tmp;
    }else{
        q->front = q->rear = tmp;
    }
    return 1;
}
int DeQ(struct Queue* q, int *pitem){
    if (q->front == NULL) return 0;
    struct QNode* tmp;
    tmp = q->front;
    *pitem = tmp->data;
    q->front = tmp->next;
    free(tmp);
    if (q->front == NULL) q->rear = NULL;
    return 1;
}
 
 
int main(){
    struct Queue *q;
    q = init();
    int item;
    
    EnQ(q,3);
    EnQ(q,5);
    DeQ(q,&item);
    printf("%d\n",item);
    EnQ(q,2);
    EnQ(q,1);
    EnQ(q,0);
    EnQ(q,9);
    DeQ(q,&item);
    printf("%d\n",item);
    DeQ(q,&item);
    printf("%d\n",item);
    DeQ(q,&item);
    printf("%d\n",item);
    DeQ(q,&item);
    printf("%d\n",item);
    DeQ(q,&item);
    printf("%d\n",item);
    DeQ(q,&item);
    printf("%d\n",item);
    DeQ(q,&item);
    printf("%d\n",item);
    destroy(&q);
    return 0;
}
 
 
 </span>


你可能感兴趣的:(队列,线性表)