/*
带头结点的链队列
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;
}
带头结点的链队列实现(C语言)
最新推荐文章于 2024-10-02 23:22:52 发布