(1)双向链表的创建与单向链表是类似的。其核心也是结点的内存申请以及结点间前后趋关系。
创建如下双链表:
using namespace std;
typedef int type;
typedef struct node
{
type data;
struct node *pre;
struct node *next;
}Node,*pNode;
//创建双向链表
pNode CreateDoubleList(type *val,int n)
{
pNode head,temp;
head=(pNode)malloc(sizeof(Node));
if(NULL==head)
{
printf("申请头结点内存失败!");
return NULL;
}
head->pre=NULL;
head->next=NULL;
temp=head;
for(int i=0;i<n;i++)
{
pNode newNode=(pNode)malloc(sizeof(Node));
if(NULL==newNode)
{
printf("申请新结点内存失败!");
return NULL;
}
newNode->data=val[i];
temp->next=newNode;
newNode->pre=temp;
newNode->next=NULL;
temp=newNode;
}
return head;
}
//打印双向链表
void printDoubleList(pNode head)
{
if(NULL==head->next)
printf("链表为空!");
pNode temp=head->next;
while(NULL!=temp)
{
printf("%3d",temp->data);
temp=temp->next;
}
printf("\n");
}
运行结果为
(2)向双向链表中插入一个结点。分为所插入结点号是否是为尾结点,应分类写出相关代码。
本文中,在第5结点后插入数据为31的结点,代码如下:
//双链表中插入一个结点
pNode InsertNode(pNode head,int num,type data)
{
pNode temp,p;
int m=ListLength(head); //双链表长度
temp=head;
p=(pNode)malloc(sizeof(Node));
if(NULL==p)
{
printf("申请内存失败!");
return NULL;
}
p->data=data;
if(num==m)
{
temp=temp->next;
while(NULL!=temp->next)
{
temp=temp->next;
}
p->next=NULL;
temp->next=p;
p->pre=temp;
return head;
}
else if((num>0)&&(num<m))
{
while(num) //查找到要插入结点的位置
{
temp=temp->next;
num--;
}
p->next=temp->next;
temp->next->pre=p;
temp->next=p;
p->pre=temp;
return head;
}
else
{
return NULL;
}
}
运行结果为:
(3)删除一个结点 找到删除结点的前一结点,并对前后关系进行处理、
代码如下:
//双链表中输出一个结点
pNode DeleteNode(pNode head, int num)
{
pNode temp =head;
int m=ListLength(head); //双链表长度
if((num>0)&&(num<=m))
{
while(num>1) //找到要删除结点的前一结点
{
temp=temp->next;
num--;
}
temp->next=temp->next->next;
temp->next->next->pre=temp;
return head;
}
else
{
printf("结点号越界!");
return NULL;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
type a[6]={11,13,14,15,17,19};
pNode head=CreateDoubleList(a,6);
printDoubleList(head);
pNode p=InsertNode(head,5,31);
printDoubleList(p);
pNode tp=DeleteNode(p,5);
if(NULL!=tp)
{
printf("删除结点成功!\n");
printDoubleList(tp);
}
else
printf("删除结点失败!");
return 0;
}
运行结果为