《数据结构》实验三:单链表

《数据结构》实验三:                 线性表综合实验 
一.实验目的 

     巩固线性表的数据结构的存储方法和相关操作,学会针对具体应用,使用线性表的相 关知识来解决具体问题。

 二.实验时间 

   准备时间为第 7 周到第 8 周,具体集中实验时间为第 4 周第 2 次课。2 个学时。 

三.实验内容 

1.建立一个由 n 个学生成绩的顺序表,n 的大小由自己确定,每一个学生的成绩信息由自己 确定,实现数据的对表进行插入、删除、查找等操作。分别输出结果。 要求如下: 1)用顺序表来实现。 2)用单链表来实现。 3)用双链表实现。 4)用静态链表实现。 5)用间接寻址实现。 分开写程序,可以一个方法分别写一博客文章上交作业。 2.实现两个集合的相等判定、并、交和差运算。要求:   1)自定义数据结构   2)自先存储结构,并设计算法。在 VC 中实现。 以上三题,第 1 题必须完成。第 2 和第 3 题可以作为选做题。 

四.实验报告 

1.在博客中先写上实习目的和内容,画出主要操作运算算法图,然后分别上传程序代码。插 入调试关键结果截图。 2.单独写一个博文,比较总结线性表的几种主要存储结果。 

#include<iostream.h>
struct Node
{
int data;
Node *next;
};
class Student
{
public:
Student();
Student(int stu[],int n);
~Student();
int Locate(int x);
void Insert(int i,int x);
int Delete(int i);
void PrintList();
private:
Node *first;
};
Student::Student()
{
first=new Node;
first->next=NULL;
}


Student::Student(int stu[],int n)
{
Node *r,*s;
first=new Node;
r=first;//尾指针初始化
for(int i=0;i<n;i++)
{
s=new Node;
s->data=stu[i];
r->next=s;r=s;
}
r->next=NULL;
}


Student::~Student()
{
Node *q=NULL;
while (first!=NULL)
{
q=first;
first=first->next;
delete q;
}
}


void Student::Insert(int i,int x)
{
Node *p=first,*s=NULL;
int count =0;
while(p!=NULL&&count<i-1)//工作指针后移
{
p=p->next;
count++;
}
if(p==NULL)throw"位置";
else
{s=new Node;s->data=x;s->next=p->next;p->next=s;}
}


int Student::Delete(int i)
{
Node *p=first,*q=NULL;
int x;
int count=0;
while(p!=NULL&&count<i-1)//查找第i-1个节点
{
p=p->next;
count++;
}
if(p==NULL||p->next==NULL)throw"位置";
else
{q=p->next;x=q->data;p->next=q->next;delete q;return x;}
}


int Student::Locate(int x)
{
Node *p=first->next;
int count=1;
while(p!=NULL)
{if(p->data==x)return count;
p=p->next;count++;}
return 0;
}


void Student::PrintList()
{
Node *p=first->next;
while(p!=NULL)
{cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
void main()
{
int r[5];
int i,a,b,c,d,n;
for(i=0;i<5;i++)
{cout<<"请输入成绩:"<<endl;
cin>>n;
r[i]=n;}
Student L(r,5);
cout<<"学生的成绩为:"<<endl;
L.PrintList();
cout<<"请输入插入的位置和插入的成绩:"<<endl;
cin>>a;
cin>>b;
try
{
L.Insert(a,b);
}
catch(char *s)
{cout<<s<<endl;}
cout<<"执行插入操作学生成绩为:"<<endl;
L.PrintList();
cout<<"请输入要查找的成绩:"<<endl;
cin>>c;
cout<<"目标成绩在第"<<L.Locate(c)<<"位"<<endl;
cout<<"请输入删除第几位的成绩,删除前数据为:"<<endl;
L.PrintList();
cin>>d;
try{L.Delete(d);}
catch(char *s)
{cout<<s<<endl;}
cout<<"删除后的数据为:"<<endl;
L.PrintList();
}





猜你喜欢

转载自blog.csdn.net/Wayne_Xiaowei/article/details/80205788