双链表在一定程度上就是单链表的的基础上加上了一个指针域,在一些情况下能够使程序更加健壮和速率更加高效。
双链表的结点定义
typedef struct node
{
int data;
struct node *next;
struct node *prior;
}node;
双链表的定义
typedef struct doublelist
{
node *head;
node *tail;
size_t size;
}doublelist;
链表的初始化
doublelist *list;
list = (doublelist *)malloc(sizeof(doublelist));
list->head = NULL;
list->tail = NULL;
list->size = 0;
头插:
1.在每次插入新结点是进行一次该双链表是否为空的判断,若为空则头结点为创建的新结点。
list->head = newnode;
list->tail = newnode;
2.若链表不为空:
newnode->next = list->head;//当链表为空时插入头结点时,头结点等于尾结点
list->head->prior = newnode;
list->head = newnode;
尾插:
在插入之前进行一次判断
1.链表为空链表时:
list->tail = newnode;
list->head = newnode;
2.链表不为空时:
newnode->prior = list->tail;
list->tail->next = newnode;
list->tail = newnode;
双链表的遍历
1.正向遍历
node *tmp;
tmp = list->head;
while(tmp){
printf("%d\n",tmp->data);
tmp = tmp->next;
}
2.反向遍历
node *tmp;
tmp = list->tail;
while(tmp){
printf("%d\n",tmp->data);
tmp = tmp->next;
}
具体的代码实现:github中zou-ting-rong/sample
原文地址:https://www.cnblogs.com/zoutingrong/p/12180416.html