链队c语言实现程序,带头结点的链队列实现(C语言)

/*

带头结点的链队列

vs2010 调试

*/

#include

#include

#include

#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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值