1.双链表的定义
双向链表基于单链表。单链表是单向的,有一个头结点,一个尾结点,要访问任何结点,都必须知道头结点,不能逆着进行。而双链表添加了一个指针域,通过两个指针域,分别指向结点的前结点和后结点。这样的话,可以通过双链表的任何结点,访问到它的前结点和后结点。
在双向链表中,结点除含有数据域外,还有两个链域,一个存储直接后继结点的地址,一般称为右链域;一个存储直接前驱结点地址,一般称之为左链域。
双向链表结构示意图:
/*随机数的范围*/#define MAX 10e/*节点结构*/
typedef struct Node
{
struct Node *pre;
int data;
struct Node *next;
}Node;
2.双向链表的创建
Node *creatList(Node *head,int length)
{
if (length == 1)
{
return( head = creatNode(head));
}
else
{
head = creatNode(head);
Node *list=head;
for (int i=1; i<length; i++)
/*创建并初始化一个新结点*/
{
Node *body=(Node*)malloc(sizeof(Node));
body->pre=NULL;
body->next=NULL;
body->data=rand()%MAX;
/*直接前趋结点的next指针指向新结点*/
list->next-body;
/*新结点指向直接前趋结点*/
body->pre=list;
/*把body指针给1ist返回*/
list=list->next;
}
}
return head;
}
3.双向链表的插入
添加至表头
添加至表的中间位置
添加至表尾
/*在第add位置的前面插入data节点*/
Node *insertListHead (Node *head,int add ,int data)
{
/*新建数据域为data的结点*/
Node *temp=(Node*)malloc(sizeof(Node)) ;
if(head == NULL)
{
printf( "malloc error! \r\n");return NULL;
}
else
{
temp->data=data;
temp->pre=NULL;
temp->next=NULL;
}
/*插入到链表头,要特殊考虑*/
if (add==1)
{
temp->next=head;
head->pre=temp;
head=temp;
}
else
{
Node * body=head;
/*找到要插入位置的前一个结点*/
for (int i=1; i<add-1; i++)
{
body=body->next;
}
/*判断条件为真,说明插入位置为链表尾*/
if (body->next==NULL)
{
body->next=temp;
temp->pre=body;
}
else
{
body->next->pre=temp;
temp->next=body->next;
body->next=temp;
temp->pre=body ;
}
}
return head;
}
/*在第add位置的后面插入data节点*/
Node *insertListEnd(Node *head,int add,int data)
{
int i = 1;
/*新建数据域为data的结点*/
Node *temp=(Node*)malloc(sizeof(Node)) ;
temp->data=data;
temp->pre=NULL;
temp->next=NULL;
Node *body=head;
while ((body->next)&&(i<add+1))
{
body=body->next;
i++;
}
/*判断条件为真,说明插入位置为链表尾*/
if (body->next==NULL)
{
body->next=temp;
temp->pre=body ;
temp->next=NULL;
}
else
{
temp->next=body->pre->next;
temp->pre=body->pre;
temp->pre=body->pre;
body->pre->next=temp;
}
return head;
}
4.双向链表的删除
Node *deleteList(Node *head,int data)
{
Node *temp=head;
/*遍历链表*/
while (temp)
{
/*判断当前结点中数据域和data是否相等,若相等,摘除该结点*/
if (temp->data==data)
{
/*判断是否是头结点*/
if(temp->pre == NULL)
{
head=temp->next;
temp->next=NULL;
free(temp);
return head;
}
/*判断是否是尾节点*/
else if(temp->next ==NULL)
{
temp->pre->next=NULL;free(temp);
return head;
}
else
{
temp->pre->next=temp->next;
temp->next->pre=temp->pre;
free(temp);
return head;
}
}
temp=temp->next;
}
printf ("can not find %d! \r\n", data);
return head;
}
5.双向链表的更改
Node *modifyList(Node *p,int add,int newElem)
{
Node *temp=p;
/*遍历到被删除结点*/
for (int i=1; i<add; i++)
{
temp=temp->next;
}
temp->data=newElem;
return p;
}
6.双向链表的查找
/*head为原双链表,elem表示被查找元素*/
int findList(Node *head,int elem)
{
/*新建一个指针t,初始化为头指针head*/
Node *temp=head;
int i=1;
while (temp)
{
if (temp->data==elem)
{
return i ;
}
i++;
temp=temp->next;
}
/*程序执行至此处,表示查找失败*/
return -1;
}
7.双向链表的打印
void printList(Node *head)
{
Node *temp=head;
while (temp)
{
/*如果该节点无后继节点,说明此节点是链表的最后一个节点*/
if (temp->next==NULL)
{
printf("%d\n", temp->data);
}
else
printf("%d->", temp->data);
}
temp=temp->next;
}
}
测试结果