看完内核中的链表操作部分,写了个通用队列

通用队列

/*
 *filename:queue.c tongyong_queue
 *time: 2014-10-24
 *
 */
#include <stdio.h>
#include <stdlib.h>

#define list_entry(ptr, type, member) ((type *)((char *)(ptr) - (unsigned long)(&((type *)0)->member)))
/*
 *宏里面的参数说明
 *ptr 是一个指向Linklist通用链的指针
 *type 是一个包含Linklist的自定义的结构的类型
 *member 是自定的结构中类型为Linklist的域
 */

//定义通用链的数据结构
typedef struct node 
{
	struct node *next;
}Linklist;

//定义队列的数据结构
typedef struct Qnode
{
	Linklist *front;
	Linklist *rear;
}Queue;

//定义自己的节点,包含Linklist
typedef  struct mynode
{
	int data;
	Linklist List;
}Mynode;

//函数声明
void initial_queue(Queue *q);
void inQueue(Queue *q, Linklist *p);
Linklist *outQueue(Queue *q);
int isEmpty(Queue *q);

//队列初始化
void initial_queue(Queue *q)
{
	q->front = q->rear = NULL;
}

//入队操作
void inQueue(Queue *q, Linklist *p)
{
	if(q->front == NULL)
	{	
		q->front = q->rear = p;
	}
	else
	{
		q->rear->next = p; //尾插法
		q->rear = p;
	}
}

//出队操作
Linklist *outQueue(Queue *q)
{
	Linklist *t = NULL;
	if(q->front == NULL )
	{
		return NULL;
	}
	t = q->front;
	q->front = t->next; //相当于删除了一个结点
	if(q->front == NULL) //若当前结点是最后一个结点
	{
		q->rear = NULL;
	}
	return t;	
}

int isEmpty(Queue *q)
{
	if(q->front == NULL) 
		return 1;
	else
		return 0;
}


int main()
{
	Queue q;
	Mynode node1, node2, node3, *h;
	Linklist *hh;

	initial_queue(&q);

	printf("inQueue: ");
	node1.data = 1;
	inQueue(&q, &(node1.List));
	printf("%d ", node1.data);

	node2.data = 2;
	inQueue(&q, &(node2.List));
	printf("%d ", node2.data);

	node3.data = 3;
	inQueue(&q, &(node3.List));
	printf("%d ", node3.data);
	
	printf("\noutQueue: ");
	hh = outQueue(&q);
	h = list_entry(hh, Mynode, List);
	printf("%d ", h->data); 
	
	hh = outQueue(&q);
	h = list_entry(hh, Mynode, List);
	printf("%d ", h->data); 
	
	hh = outQueue(&q);
	h = list_entry(hh, Mynode, List);
	printf("%d\n", h->data); 

	return 0;
}


 
 
 
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值