1. 程式人生 > >帶頭結點的鏈佇列實現(C語言)

帶頭結點的鏈佇列實現(C語言)

/*
	帶頭結點的鏈佇列
	vs2010 除錯
*/

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

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0

typedef struct queue_node qnode;

typedef struct queue_node
{
	int data;
	qnode *next;
};

typedef struct link_queue
{
	qnode *head;
	qnode *tail;
}lqueue;

/*
函式功能:	鏈佇列初始化
*/
int init_link_queue(lqueue *Q)
{
	qnode *tmp_node = (qnode *)malloc(sizeof(qnode));
	if(!tmp_node)
	{
		return ERROR;
	}

	tmp_node->next = NULL;
	Q->head = tmp_node;
	Q->tail = tmp_node;

	return OK;
}

/*
函式功能:	佇列是否為空
返 回 值:	1 空; 0 非空
*/
int is_queue_empty(lqueue Q)
{
	return ((Q.head == Q.tail) ? TRUE : FALSE);
}

/*
函式功能:	元素num入隊
*/
int enqueue(lqueue *Q, int num)
{
	qnode *tmp_node = (qnode *)malloc(sizeof(qnode));
	if(!tmp_node)
	{
		return ERROR;
	}

	tmp_node->next = NULL;
	tmp_node->data = num;
	Q->tail->next = tmp_node;
	Q->tail = tmp_node;

	return OK;
}

/*
函式功能:	出隊,隊頭元素存入num
*/
int dequeue(lqueue *Q, int *num)
{
	qnode *tmp_node = NULL;
	if(is_queue_empty(*Q))
	{
		return ERROR;
	}

	tmp_node = Q->head->next;
	Q->head->next = tmp_node->next;
	*num = tmp_node->data;

	if(Q->head->next == NULL)
	{
		Q->tail = Q->head;
	}

	free(tmp_node);

	return OK;
}

/*
函式功能:	獲取隊頭元素,存入num
*/
int get_elem(lqueue Q, int *num)
{
	if(is_queue_empty(Q))
	{
		return ERROR;
	}

	*num = Q.head->next->data;

	return OK;
}

/*
函式功能:	列印佇列元素
*/
void print_queue(lqueue Q)
{
	lqueue tmpQ = Q;
	tmpQ.head = (qnode *)malloc(sizeof(qnode));
	tmpQ.head = Q.head->next;
	printf("Head->*->");

	while(tmpQ.head != NULL)
	{
		printf("%d->", tmpQ.head->data);
		tmpQ.head = tmpQ.head->next;
	}

	free(tmpQ.head);
	printf("TAIL\n");
}

/*
函式功能:	銷燬佇列
*/
void destory_queue(lqueue *Q)
{
	qnode *tmp_node = NULL;
	while(Q->head->next != NULL)
	{
		tmp_node = Q->head->next;
		Q->head->next = tmp_node->next;

		free(tmp_node);
	}
}

/*
函式功能:	獲得佇列長度
返 回 值:	長度
*/
int get_queue_length(lqueue Q)
{
	int length = 0;
	lqueue tmpQ;
	tmpQ.head = (qnode *)malloc(sizeof(qnode));
	tmpQ.head = Q.head->next;

	if(is_queue_empty(Q))
	{
		return length;
	}

	do 
	{
		length++;
		tmpQ.head = tmpQ.head->next;
	}while(tmpQ.head != NULL);

	free(tmpQ.head);

	return length;
}

int main(int argc, char *argv[])
{
	int num = 0;
	lqueue queue;

	init_link_queue(&queue);

	enqueue(&queue, 7);
	enqueue(&queue, 8);
	enqueue(&queue, 9);
	enqueue(&queue, 6);
	printf("length = %d\n", get_queue_length(queue));
	print_queue(queue);

	dequeue(&queue, &num);	
	printf("length = %d, dequeue num = %d\n", get_queue_length(queue), num);
	print_queue(queue);

	destory_queue(&queue);
	return 0;
}