#include <stdlib.h>
typedef struct _LIST
{
struct _LIST *previous;
struct _LIST *next;
}LIST;
/*
* List initialization
*/
void list_init(LIST *list_head)
{
list_head->next = list_head;
list_head->previous = list_head;
}
/*
* return TRUE if the list is empty
*/
int is_list_empty(LIST *list)
{
return (list->next == list);
}
/*
* add element to list
* add element before head.
*/
void list_insert(LIST *head, LIST *element)
{
element->previous = head->previous;
element->next = head;
head->previous->next = element;
head->previous = element;
}
/*
* delete element from list
*/
void list_delete(LIST *element)
{
element->previous->next = element->next;
element->next->previous = element->previous;
}
int main(void)
{
LIST *head = (LIST *)malloc(sizeof(LIST));
LIST *list1 = (LIST *)malloc(sizeof(LIST));
LIST *list2 = (LIST *)malloc(sizeof(LIST));
list_init(head);
list_insert(head, list1);
list_insert(list1, list2);
return 0;
}
以上代码单步调试,在watch窗口中对变量进行跟踪可以看到,head指针的next指向list2,list1的next指向head,list2的next指向list1,如此行成一个循环。并且注意list_insert函数是往前插入(previous)。
对于list_insert函数的实现可以这样来看:首先你要将一个element插入一个链表,并且插在head前面,你先要对该element的previous和next的进行操作,next肯定指向head了,而previous需要指向插入前head的previous;然后,你需要对head的prevous指针进行重新操作,既然插入它的前面,当然previous应指向element;最后,还需要改变element前一个元素的next指针,也要让它指向element,而得到这个指针即通过head->previous->next即可。因此总结在循环双向链表中插入一个element需要改变4个指针指向(element本身两个+head的previous+原head的previous的next)。
注:以上关于LIST的代码来自于raw-os。