C之队列

用C实现的一个简单的队列

list.h

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

struct LinkList
{
	int score;
	struct LinkList *next;
};

typedef struct LinkList List;

测试例子

#include "list.h"

typedef struct Queue{
	int list_count;
	List *head,*tail;
} Queue;

Queue t_queue;

void queue_init(Queue *q)
{
	q->head = NULL;
	q->tail = NULL;
	printf("init Queue successful !!! \n");
}

int queue_put(Queue *q,int score)
{
	List *tamp;
	tamp = (List*) malloc(sizeof(List));

	tamp->score = score;
	tamp->next = NULL;

	if(q->tail == NULL)
	{
		q->head = tamp;
	}else
	{
		q->tail->next = tamp;
	}

	q->tail = tamp;
	q->list_count++;

	return 0;
}

int queue_get(Queue *q)
{
	int score;
	List *tamp;
	tamp = (List*) malloc(sizeof(List));

	if(q->head == NULL)
	{// 队列为空
		printf("Queue is NULL!!! \n");
	}else
	{
		while(q->head != NULL)
		{
			tamp = q->head;// 先拿到对列头
			q->head = tamp->next;// 然后重新给队列头赋值->相当于原先的队列头被删除了
			q->list_count--;
			score = tamp->score;
			printf("now queue count = %d ,score = %d   !!!\n",q->list_count,score);

			if(q->head == NULL)
			{// 如果新的队列头为空了,队列也就空了
				q->tail = NULL;
				break;
			}
		}
		return score;
	}

	return 0;
}

int main(int argc, char **argv) {
	// 初始化队列
	queue_init(&t_queue);
	// 往队列中存放数据
	int j = 150;
	while (j < 153)
	{
		queue_put(&t_queue,j);
		j++;
	}

	// 从队列中取数据
	queue_get(&t_queue);

	return 0;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值