您的位置:首页 > 其它

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

2014-10-24 23:56 309 查看
通用队列

/*
*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;
}






内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: