<5>Queue队列 链式存储实现

https://github.com/liutianshx2012/Algorithms-Data_structures/tree/master/Data_structures/src2

//
// Queue.h
// Algorithms&Data_structures
//
// Created by TTc on 15-2-2.
// Copyright (c) 2015年 TTc. All rights reserved.
//

#ifndef __Algorithms_Data_structures__Queue__
#define __Algorithms_Data_structures__Queue__

#include <stdio.h>
#include "list.h"
typedef List Queue;
/* Public Interface */
#define queue_init list_init

#define queue_destroy list_destroy

int queue_enqueue(Queue *queue,const void *data);

int queue_dequeue(Queue *queue,void **data);

#define queue_peek(queue)  ((queue) ->head == NULL? NULL:(queue)->head->data)
#define queue_size list_size
#endif /* defined(__Algorithms_Data_structures__Queue__) */
//
// Queue.c
// Algorithms&Data_structures
//
// Created by TTc on 15-2-2.
// Copyright (c) 2015年 TTc. All rights reserved.
//

#include "queue.h"
#include <stdlib.h>
//入队操作
int
queue_enqueue(Queue *queue,const void *data){
    return list_ins_next(queue, list_tail(queue), data);
}
//出队操作
int
queue_dequeue(Queue *queue,void **data){
    return list_rem_next(queue, NULL, data);
}
//
// test_queue_main.c
// 
//
// Created by TTc on 16/5/25.
//
//

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include "list.h"
#include "queue.h"

/* destroy */
void destroy(void *data)
{
    printf("in destroy\n");
    free(data);
    return;
}


/* main */
int main(int argc, char **argv)
{
    Queue queue;

    int *int_ptr = NULL;
    int ret;
    int i;

    //init queue
    queue_init(&queue, destroy);

    //enqueue;
    for(i = 0; i < 5; i++ )
    {
        int_ptr = NULL;
        int_ptr = (int *)malloc(sizeof(int));
        if( int_ptr == NULL )
            return -1;
        printf("enqueue: data = %d\n",i);
        *int_ptr = i;
        ret = queue_enqueue(&queue, (void *)int_ptr);
        if( ret != 0 )
            return -1;
    }

    printf("the size of the queue: %d\n", queue_size(&queue));

    for(i = queue_size(&queue); i > 0 ; i-- )
    {
        int_ptr = NULL;
        ret = queue_dequeue(&queue, (void **)&int_ptr);
        if( ret != 0 )
            return -1;
        printf("i = %d, dequque data = %d\n",i, *int_ptr);
    }

    printf("after dequeue the size of the queue: %d\n",queue_size(&queue));
    return 0;
}

<5>Queue队列 链式存储实现_第1张图片

你可能感兴趣的:(<5>Queue队列 链式存储实现)