**学院
本科实验报告(**-**学年第一学期)
课程名称:数据结构实验
任课教员:
系:
专业:
年月日
**学院
《数据结构》课程实验报告
实验项目名称:单链表的插入与删除
系()::专业:指导教员:
姓名:学号:成绩:
同组姓名:
实验地点:
1.实验项目名称:单链表的查找、插入与删除
2.实验目的和要求:设计算法,实现线性结构上的单链表的产生以及元素的查找、插入与删除。
通过该算法的设计和C语言程序实现,熟悉针对单链表作为存储结构的线性表上的查找、插入、删除等基本操作的实现方法。
3.实验原理:单链表采用链式存储结构,具有指针域和数据域。
4.实验内容:
1)从键盘输入20个整数,产生不带表头的单链表,并输入结点
值。
2)从键盘输入1个整数,在单链表中查找该结点的位置。
若找到,则显示“找到了”;否则,则显示“找不到”。
3)从键盘输入2个整数,一个表示欲插入的位置i,另一个表示欲插入的数值x,将x插入在对应位置上,输出单链表所有结点值,观察输出结果。
4)从键盘输入1个整数,表示欲删除结点的位置,输出单链表所有结点值,观察输出结果。
5.实验环境:Windows2000 visual studio c++
6.操作方法与实验步骤:
(1)实验原代码(c语言版):
#include<stdio.h>
typedef int ElemType;
#include <stdlib.h> /* For _MAX_PATH definition */
#include <malloc.h>
/* 单链表结构的定义*/
typedef struct LNode {
ElemType data;
struct LNode *next;
};
typedef struct LNode *LinkList;
LinkList CreatList_L(struct LNode **L,int n)
{ /*建立带表头结点的单链表L,n为单链表的大小*/ int i;
struct LNode *p,*q;
p=(struct LNode *)malloc(sizeof (struct LNode));
(*L)=p;
printf("请输入第1个数.");
scanf("%d",&(p->data));
for(i=n-1;i>0;--i)
{ q=(LinkList)malloc(sizeof(struct LNode));/*生成新结点*/ printf("请输入第%d个数.",n-i+1);
scanf("%d",&(q->data));
p->next=q;
p=q;
}p->next=NULL;
return (*L);
}
void print(int c)
{ printf("\t%d",c);
}/*打印函数*/
void FindList(struct LNode *La,ElemType f)
{ struct LNode *cur;
int i=1,u=1;
cur=La;
while(cur !=NULL)
{++i;
if(cur->data==f)
{
printf("在链表中找到了你输入的数字。
\n");
printf("它的位置是%d\n",i-1);
u++;
}/*if*/
cur=cur->next;
}/*while*/
if(u==1)
printf("在链表中找不到你输入的数字。
\n");
}/*查找函数*/
LinkList InsertList(struct LNode *L,int i,int x)
{ struct LNode *q,*p;
int j;
p=L;
q=(struct LNode *)malloc(sizeof(struct LNode));
q->data=x;
if(i==1) {q->next=L;return q;}
else {for(j=1;j<i-1;j++) L=L->next;
q->next=L->next;
L->next=q;
return p;}
}/*插入函数*/
LinkList DeleteList(struct LNode *L, int x) { int i;
if(x==1) L=L->next;
else{ for(i=1;i<x-1;i++)
L=L->next;
L->next=L->next->next;
}
return (L);
}/*删除函数*/
void main()
{ int SIZE,e,Location;
struct LNode La;
struct LNode *p,*l,*head;
l=&La;
printf("请输入链表的大小:");
scanf("%d",& SIZE);
head=CreatList_L(&l,SIZE);
printf("一个新链表已经建立。
\n它是:");
for(p=l;p!=NULL;p=p->next)
print(p->data);//for
printf("\n");
printf("现在开始实验的第二部分\n");
printf("请输入你要查找的数字。
\n");
scanf("%d",&e);
FindList(l,e);
printf("请从键盘输入2个整数,一个表示欲插入的位置Location,另一个表示欲插入的数值e。
\n");
printf("Location=");
scanf("%d",&Location);
printf("\n e=");
scanf("%d",&e);
head=InsertList(l,Location,e);
printf("新链表是:\n");
l=head;
for(e=1;e<=SIZE+1;e++)
{ printf(" %d ",l->data);
l=l->next;
}//for
l=head;
printf("从键盘输入1个整数,表示欲删除结点的位置.\n您要删除的位置是:");
scanf("%d",&e);
head=DeleteList(l,e);
l=head;
printf("新链表是:\n");
for(e=1;e<=SIZE;e++)
{ printf(" %d ",l->data);
l=l->next;
}//for
}
实验如下图:
7.实验结果与分析:实验过程中由于C语言应用的不熟练导致须经教员的多次纠正与指导,才能真正在计算机上实现。