• 数据结构【一】:简单队列simple queue


    简单的FIFO队列实现,非线程安全! 

    1.queue.h : abstract data type queue

    #ifndef CUR_QUEUE_H
    #define CUR_QUEUE_H
    #include<stdlib.h>
    struct node{
        int value;
        struct node * next;
    };
    
    
    typedef struct queue{
         int max,cur;
         struct node * head, * tail;
    }queue;
    
    
    extern queue* empty_queue(int _max);
    extern int queue_free(queue *q);
    extern int is_empty(const queue *q);
    extern int is_full(const queue *q);
    extern int enqueue(struct node *item, queue *q);
    extern struct node* dequeue(queue *q);
    
    #endif

    2.queue.c

    #include "queue.h"
    
    queue* empty_queue(int _max)
    {
         queue *q = malloc(sizeof(queue));
         q->head  = q->tail = NULL;
         q->max   = _max;
         q->cur   = 0;
         return q;
    }
     
    int queue_free(queue *q)
    {
        while(!is_empty(q))
            free(dequeue(q));
        free(q);
    }
    
    int is_empty(const queue *q)
    {
        return q->cur == 0;
    }
    
    int is_full(const queue *q)
    {
        return q->cur == q->max;
    }
    
    int enqueue(struct node *item, queue *q)
    {
        if(is_full(q)) return -1;
        if(is_empty(q))
            q->head = q->tail = item;
        else
        {
            q->tail->next = item;
            q->tail = item;
        }
        q->cur++;
        return 0;
    }
    
    struct node* dequeue(queue *q)
    {
        if(is_empty(q)) return NULL;
        struct node * temp = q->head;
        q->head = q->head->next;
        q->cur--;
        return temp;
    }

    3.main.c

    #include<stdio.h>
    #include<stdlib.h>
    #include "queue.h"
    
    
    void main()
    {
     int i;
     queue *q = empty_queue(5);
     
     for(i=1; i<=10; i++){
         
         struct node * item = (struct node *)malloc(sizeof(struct node));
         item->value = i;
         item->next = NULL;
    
         printf("is_full : %d
    ",is_full(q));
         if(is_full(q)) {
            printf("queue is full
    ");
            printf("enqueue : %d
    ",enqueue(item,q));
            break;
         }
         printf("enqueue : %d
    ",enqueue(item,q));
     }
    
     while(!is_empty(q))
     {
         struct node * item = dequeue(q);
         if(item != NULL){
             printf("value : %d  ,current : %d
    ", item->value,q->cur);
             free(item);
         }
     }
     queue_free(q);
    }

    测试结果:

  • 相关阅读:
    Java 开发环境配置
    JDBC数据批处理
    knockout.js简单实用教程1
    angular 入门教程1
    knockout简单实用教程3
    knockout简单实用教程2
    autofac使用笔记
    MVC WEB api 自动生成文档
    Unity IOC注入详细配置(MVC,WebApi)
    为什么php往mongo里插入整型数字8,变成了numberint(8)
  • 原文地址:https://www.cnblogs.com/coveted/p/3498067.html
Copyright © 2020-2023  润新知