首页 > 编程语言 > 详细

c语言 队列的应用

时间:2017-02-25 18:41:40      阅读:143      评论:0      收藏:0      [点我收藏+]
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
typedef struct node * PNode; /*定义队列的每个节点的类型*/
typedef struct node {
    int data;//每个节点中存放的数据
    PNode next;//下一节点
}Node;
 
typedef struct queue {
    PNode head;//队头
    PNode tail;//队尾
    int Length;//队列长度
}Queue;
 
Queue *GetQueue() { // 返回创建的新空队列
    Queue *queue = (Queue *)malloc(sizeof(Queue));
    queue->head = (Node *)malloc(sizeof(Node));
    queue->head->next = NULL;
    queue->tail = queue->head;
    queue->Length = 0;
    return queue;
}
 
void EnQueue(Queue *Q,int x) { // 将x送入队
    PNode newnode = (Node *)malloc(sizeof(Node));
    newnode->data = x;
    ++Q->Length;
    newnode->next = NULL;
    Q->tail->next = newnode;
    Q->tail = newnode;
}
 
int notEmpty(Queue *Q) {
    return (Q->Length > 0);
}
 
int DeQueue(Queue *Q,int *x) { // 将x送出队
    PNode p;
    if(notEmpty(Q)) {
        p = Q->head->next;
        *x = p->data;
        Q->head->next = p->next;
        --Q->Length;
        free(p);
        return 1;
    }
    return 0;
}
 
int GetLength(Queue *Q) { // 获取队列长度
    return Q->Length;
}
 
int GetFirst(Queue *Q) { // 获取队头数据
    return Q->head->next->data;
}
 
int GetLast(Queue *Q) { // 获取队尾数据
    return Q->tail->data;
}
 
void ClearQueue(Queue *Q) {
    Q->tail = Q->head;
    Q->Length = 0;
}
 
void DestroyQueue(Queue *Q) {
    PNode q,p = Q->head;
    while(p) {
        q = p;
        p = q->next;
        free(q);
    }
    Q->head = Q->tail = NULL;
    free(Q);
    Q = NULL;
}
 
int main() {
    int i,n = 10,x;
    Queue *Q = GetQueue();//定义一个新的队列
    srand(time(0));  //用于rand()产生随机数的前提,播种,播下time(0),那么每次运行程序得到的种子不同,产生的随机数列也就不同。
    for(i = 0; i < n; ++i) {
        x = rand() % 100;//产生一个不大于100的随机数
        printf("%d ",x);
        EnQueue(Q,x);//x送进队列
    }
    printf("\n");
    while(notEmpty(Q)) {//判断没有空队列
        DeQueue(Q,&x);//出队列
        printf("%d ",x);
    }
    printf("\n");
    return 0;
}

c语言 队列的应用

原文:http://www.cnblogs.com/cxy931980808/p/6442318.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!