软件基础基础实验报告
系别:机械班级:模具学号:1100413002 姓名:王海江实验时间:10.16 实验地点:k4
实验环境:Turbo c++3.0(vc6.0)
实验名称:线型单链表的建立、插入和删除(实验三和实验四的综合)
实验目的:
(1)学习建立单链表
(2)学会在单链表中实现数据的插入
实验内容:
定义一个单链表输入元素10,20,30,在扫描输出该单链表中的元素以及元素个数。在元素为20的结点前插入100。然后扫描输出该单链表中的元素以及元素个数。
HEAD Array
程序代码:(请写上详细的程序注释!注意这是重要的评分依据!)
#include"stdlib.h"
#include"stdio.h"
struct node
{
int d;
struct node *next;
};//建立结构体,用于存放数据和指针域
struct node *input(int *n)//建立输入函数
{//请输入代码
int x;struct node *head=NULL,*p,*q;
scanf("%d",&x);//输入数据x
while(x>0)//判断x正负
{
*n=*n+1;//空间的长度
p=(struct node*)malloc(sizeof(struct node));申请p结点
p->d=x;//
p->next=NULL;
if(head==NULL)//头指针为空
{
head=(struct node*)malloc(sizeof(struct node));//头指针指第一个结点
head=p;
}
else q->next=p;
q=p;
scanf("%d",&x);//输入x的值
}
return head;//返回函数值
}
void output(struct node *head,int *n)//建立输出函数
{
struct node *p;//
p=head;
//请输入代码
while(p!=NULL)
{
printf("%d ",p->d);
p=p->next;
}
}
struct node *lookst(struct node *head,int x)//建立查找函数
{
// 请输入查找的代码;
struct node *p;
p=head;
while((p->next!=NULL)&&(((p->next)->d)!=x))
p=p->next;
return(p);
}
struct node *inslst(struct node *head,int x,int b,int *n)//建立插入函数{
struct node *p,*q;
p=(struct node*)malloc(sizeof(struct node));
p->d=b;
if(head==NULL)
{
head=p;p->next=NULL;
return head;
}
if(head->d==x)
{
p->next=head;head=p;
return head;
}
q=lookst(head,x);//调用查找函数
p->next=q->next;
q->next=p;
*n=*n+1;
return head;
}
struct node * delst(struct node *head,int x ,int *n)//建立删除函数{
//请输入删除的代码;
struct node *p,*q;
if(head==NULL)//判断是否为空链表
{printf("not exist\n");
return head;
}
if(head->d==x)//如果链表不为空
{
p=head->next;
free(head);
head=p;
return head;
}
q=lookst(head,x);//调用查找函数
if(q->next==NULL)//查找结束
{printf("not exist!!");
return head;
}
p=q->next;q->next=p->next;
free(p);//删除查找到的元素
*n=*n-1;//链表的长度减小1
return head;
}
void main()//主函数
{
int *n,b,x;//定义变量
struct node *head;
head=NULL;
n=NULL;
n=(int *)malloc(sizeof(int));//申请空间
*n=0;//空间清零
printf("请输入元素到线性链表中:");//输入提示head=input(n);//调用输入函数
printf("线性表中的元素是:");
output(head,n);//调用输出函数
printf("\n现在请输入要插入的元素:");
scanf("%d",&b);
printf("\n请输入在那个元素前插入:");
scanf("%d",&x);
head=inslst(head,x,b,n);//调用插入函数
output(head,n);
printf("\n现在请您输入要删除的元素:");
scanf("%d",&x);
head=delst(head,x,n);//调用删除函数output(head,n);
}