双向链表的构建插入删除和显示实验报告材料.docx
《双向链表的构建插入删除和显示实验报告材料.docx》由会员分享,可在线阅读,更多相关《双向链表的构建插入删除和显示实验报告材料.docx(10页珍藏版)》请在冰豆网上搜索。
双向链表的构建插入删除和显示实验报告材料
一.实验目的:
1)掌握双向线性链表的逻辑特征
2)熟练掌握带头结点的双向链表的指针操作,能完成双向链表的构建,插入,删除与显示等复杂应用。
二.实验原理
双向链表的结点中有两个指针域,其一指向直接后继,另一指向直接前驱,在C语言中可描述如下:
typedefstructDuLNode{
ElemTypedata;
structDuLNode*prior;
structDuLNode*next;
}DuLNode,*DuLinkList;
双向链表的操作和单链表类似。
本实验利用函数以及指针处理双向链表的知识,首先建立四个函数,creat,print,ListInsert_DuL,ListDelete_DuL分别实现对双向链表的建立,输出,插入,删除功能。
还需建立GetElemP_DuL函数来辅助。
然后将五个函数组织在一个C程序中,用main函数作主调函数。
三.实验容
1.首先建立一个带头结点的非空的双向链表。
建立函数creat,操作与建立线性链表类似,但需要修改两个方向的指针。
本实验以输入6个学生的数据为例。
2.建立函数GetElemP_DuL,得到第i个元素的位置指针。
3.对链表进行插入操作。
建立函数ListInsert_DuL,输入要插入的学生数据以及位置,调用函数GetElemP_DuL,插入成功返回1,否则返回0。
4.对链表进行删除操作。
建立函数ListDelete_DuL,输入要删除的学生位置,调用函数GetElemP_DuL,删除成功返回1,否则返回0。
5.对链表的结果进行输出与显示。
建立函数print,对链表进行正向和反向的输出。
6.建立main函数,把以上五个函数整合到一个程序之中,当输入的数据不为0时可进行多次删除,插入操作,并对每一次的结果进行显示。
四.实验方法
运行环境:
VisualC++6.0
把所有程序思想写成代码,通过VisualC++编译,得到结果,即运行成功。
本实验程序代码:
#include"stdio.h"
#include"malloc.h"
#defineNULL0
#defineLENsizeof(structstudent)
#defineOK1
#defineERROR0
structstudent
{
intdata;
structstudent*prior;
structstudent*next;
};
intn;
structstudent*creat(void)
{
structstudent*L;
structstudent*p1,*p2;
L=(structstudent*)malloc(LEN);
L->next=NULL;
L->prior=NULL;
n=0;
p1=p2=(structstudent*)malloc(LEN);
scanf("%d",&p1->data);
while(p1->data!
=0)
{
n=n+1;
if(n==1)
{L->next=p1;p1->prior=L;}
else
{
p2->next=p1;
p2->next->prior=p2;
}
p2=p1;
p1=(structstudent*)malloc(LEN);
scanf("%d",&p1->data);
}
p2->next=L;
L->prior=p2;
return(L->next);
}
voidprint(structstudent*head)
{
structstudent*p;
p=head;
printf("正向输出:
\n");
if(head!
=NULL)
do{
printf("%d\n",p->data);
p=p->next;
}while(p!
=head->prior);
printf("反向输出:
\n");
if(p==head->prior)
{p=p->prior;
do{
printf("%d\n",p->data);
p=p->prior;
}while(p!
=head->prior);
}
}
structstudent*GetElemP_DuL(structstudent*L,inti)
{
structstudent*p;
intj=1;
p=L;
while(j!
=i)
{
p=p->next;
j++;
}
returnp;
}
intListInsert_DuL(structstudent*L,inti,inte)
{
structstudent*p,*s;
if(!
(p=GetElemP_DuL(L,i)))
returnERROR;
if(!
(s=(structstudent*)malloc(LEN)))
returnERROR;
s->data=e;
s->prior=p->prior;
p->prior->next=s;
s->next=p;
p->prior=s;
n=n+1;
returnOK;
}
intListDelete_DuL(structstudent*L,inti)
{
structstudent*p;
inte;
if(!
(p=GetElemP_DuL(L,i)))
returnERROR;
e=p->data;
p->prior->next=p->next;
p->next->prior=p->prior;
free(p);
n=n-1;
returnOK;
}
voidmain()
{
structstudent*head;inti,e;
printf("请输入学生的数据:
\n");
head=creat();
print(head);
printf("请输入要插入的位置以及数据:
\n");
scanf("%d%d",&i,&e);
while(e!
=0)
{
if(ListInsert_DuL(head,i,e)==1)
print(head);
printf("请输入要插入的位置以及数据:
\n");
scanf("%d%d",&i,&e);
}
printf("请输入要删除的位置:
\n");
scanf("%d",&i);
while(i!
=0)
{
if(ListDelete_DuL(head,i)==1)
print(head);
printf("请输入要删除的位置:
\n");
scanf("%d",&i);
}
}
五.实验结果
运行结果截图:
表明双向链表构建成功。
六.实验结论
可以通过指针的方法建立双向链表并对其进行插入,删除和显示操作。