双向链表的建立插入删除的方式与单链表类似,要注意的是双向链表的头部和尾部各有一个NULL指针,指示链表的结束。每个链表节点有两个指针分别是前驱指针和后继指针,指向前后两个节点。下面是双向链表的代码:
# include <stdio.h>
# include <stdlib.h>
struct list{
int num;
list *next,*prior;
};
typedef list *link;
int main()
{ link head=NULL;
void print(link);
link deletelist(link,int);
link createlist(link);
head=createlist(head);
print(head);
head=deletelist(head,1);
print(head);
system("pause");
return 0;
}
link createlist(link head)
{
int item;
link p1,p2;
head=(link)malloc(sizeof(list));
printf("input the first element\n");
scanf("%d",&head->num);
head->next=NULL;
head->prior=NULL;
p1=head;
printf("input an element\n");
scanf("%d",&item);
while(item!=-1)
{
p2=(link)malloc(sizeof(list));
p2->num=item;
p2->prior=NULL;
p2->next=p1;
p1->prior=p2;
p1=p2;
printf("input an element\n");
scanf("%d",&item);
}
return head;
}
void print(link head)
{
link p=head;
for(;p!=NULL;p=p->prior)
printf("%d\t",p->num);
printf("\n");
}
link deletelist(link head,int x)
{
link p1=head;
for(;p1->num!=x;p1=p1->prior)
{}
if(p1==head)
{
p1->prior->next=NULL;
head=p1->prior;
free(p1);
}
else if(p1->prior==NULL)
{
p1->next->prior=NULL;
free(p1);
}
else{
p1->prior->next=p1->next;
p1->next->prior=p1->prior;
free(p1);
}
return head;
}
原文:http://blog.csdn.net/u011608357/article/details/19014523