队列--双链表实现
队列是一种常见的数据结构。常用于buffer数据,因为他是先进先出,先来的数据先消耗。
最常用的操作是插入队列尾部,和读取头部数据。
通常在项目中,一个线程来buffer数据,另外一个线程来消耗数据。
下面给出队列的常用方法,并写一个简单的验证程序。
#include <stdlib.h>
#include <stdio.h>
typedef struct _ListNode{
struct _ListNode *prev;
struct _ListNode *next;
int data;
}ListNode;
typedef struct _List{
ListNode *head;
ListNode *tail;
int len;
}List;
void list_init(List *pList)
{
pList->head = NULL;
pList->tail = NULL;
pList->len = 0;
}
void list_insert_tail(List *pList, ListNode *node)
{
node->next = NULL;
if ((node->prev = pList->tail) != NULL)
{
pList->tail->next = node;
}
else
{
pList->head = node;
}
pList->tail = node;
pList->len++;
}
void list_remove(List *pList, ListNode* node)
{
if (pList->tail == node)
{
pList->tail = node->prev;
}
else
{
node->next->prev = node->prev;
}
if (pList->head == node)
{
pList->head = node->next;
}
else
{
node->prev->next = node->next;
}
if (node != NULL)
{
node->prev = node->next = NULL;
}
}
int main(void)
{
List _list;
ListNode *pListNode;
list_init(&_list);
int idx = 0;
for (idx = 0; idx < 10; idx++)
{
pListNode = (ListNode*)malloc(sizeof(ListNode));
pListNode->data = idx;
pListNode->prev = NULL;
pListNode->next = NULL;
list_insert_tail(&_list,pListNode);
}
ListNode *tmp;
printf("head:%d, tail:%d, len:%d\n", _list.head->data, _list.tail->data,_list.len);
for (tmp = _list.head; tmp != NULL; tmp = tmp->next)
{
printf("list node:%d\n", tmp->data);
}
for (idx = 0; idx < 10; idx++)
//for (tmp = _list.head; tmp != _list.tail; tmp = tmp->next)
{
tmp = _list.head;
printf("remove list head:%d\n", _list.head->data);
list_remove(&_list, tmp);
}
return 0;
}
运行结果如下: