c队列操作

队列实际应用现场:先入先出
#include "queue.h"
#include "linkedlist.h"
#include <stdlib.h>
#include <stdio.h>

#ifdef DMALLOC
#include "dmalloc.h"
#endif
typedef struct {
    LinkedList *list;
} Queue;
Queue *queue_construct() {

    Queue *queue = NULL;

   	/*
     * Allocate space for the object and set all fields to zero.
     */
    queue = calloc(1, sizeof(Queue));

	if (queue == NULL) {
        return NULL;
    }
		
    /*
     * Instantiate an internal linked list to hold queue's elements.
     */
	queue->list = linked_list_construct();
	
	if (queue->list == NULL) {
        return NULL;
    }
	
    return queue;
}

void queue_destroy(Queue *queue) {

    if (queue == NULL) {
        return;
    }
    
    /*
     * Delete the linked list that holds the elements.
     */
	linked_list_destroy(queue->list);
	queue->list = NULL;
	
    free(queue);
}

void queue_enqueue(Queue *queue, const void *data) {
	
	LinkedListNode *list_node = NULL;
	
	if (queue == NULL) {
        return;
    }
	
	list_node = linked_list_node_construct(data);
	
    /*
     * Add the node to the end of this
     */
	linked_list_append_node(queue->list, list_node);
	
}

const void *queue_dequeue(Queue *queue) {

	LinkedListNode *list_node = NULL;
    const void *data = NULL;
	
	if (queue == NULL) {
        return NULL;
    }
	
	linked_list_seek_start(queue->list);
	
	list_node = linked_list_get_next_node(queue->list);
	
	if (list_node == NULL) {
        return NULL;
    }
		
	data = linked_list_node_get_data(list_node);
	
	linked_list_remove_node(queue->list, list_node);
	
	return data;

}

int queue_is_empty(Queue *queue) {
	
	if (queue == NULL) return 1;
		
	return linked_list_is_empty(queue->list);

}
posted @ 2011-09-27 12:39  火腿骑士  阅读(368)  评论(2编辑  收藏  举报