上一篇博文介绍了如何使用C语言实现单链表,这篇博文介绍下双向链表的实现。单链表中每个结点只有一个后驱,而双向链表中每个结点都有一个后驱和前驱(除了第一个结点只有一个后驱,最后一个结点只有一个前驱)。双向链表中每个结点具有一个数据域和两个指向前一个结点和后一个结点的指针域。代码的实现:
首先得创建一个结点的结构体:Double_Node
typedef struct Double_Node
{
int data;
Double_Node *front;
Double_Node *next;
}Double_Node,*DoubleLink;下面编写一个创建结点的函数:Create_Node(int),参数为创建的这个结点的数据域的数据:
DoubleLink Create_Node(int value)
{
DoubleLink p=NULL;
p=new Double_Node;
p->data=value;
p->next=NULL;
return p;
}接下来编写创建特定长度的双向链表的函数Create_Link(int),参数为创建的这个双向链表的长度:
DoubleLink create_Link(int number)
{
if(number==0) return false;
int x=0;int y=0;
cin>>y;
DoubleLink p1=Create_Node(y);
DoubleLink head=p1;
p1->front=NULL;x++;
DoubleLink p2;
while(x<number)
{
cin>>y;
p2=Create_Node(y);
p1->next=p2;
p2->front=p1;
p1=p2;
x++;
}
p1->next=NULL;
return head;
}下面是往双向链表中插入结点的函数:insertValue(DoubleLink &,int ),第一个参数为待插入的双向链表的表头,第二个参数为待插入的结点的数据域的数据:
bool insert_Value(DoubleLink &D,int e)
{
DoubleLink temp=Create_Node(e);
DoubleLink head=D;
if(e<head->data)
{
temp->front=NULL;
temp->next=head;
head->front=temp;
D=temp;
return true;
}
while(head->next)
{
if(head->data>e)
{
temp->front=head->front;
head->front->next=temp;
temp->next=head;
head->front=temp;
return true;
}
head=head->next;
}
if(head->data>e)
{
temp->front=head->front;
head->front->next=temp;
temp->next=head;
head->front=temp;
}
else
{
head->next=temp;
temp->front=head;
temp->next=NULL;
}
return true;
}最后编写一个程序测试双向链表的代码:实现输入特定数目的整型数据,然后以升序的顺序输出:
void main()
{
DoubleLink head=NULL;
int x=0;
int N=0;
cout<<"准备输入数据的个数:";
cin>>N;
head=create_Link(1);
for(int i=0;i<N-1;i++)
{
cin>>x;
insert_Value(head,x);
}
while(head!=NULL)
{
cout<<head->data<<" ";
head=head->next;
}
}测试的结果为:
原文:http://blog.csdn.net/daida2008/article/details/38145813