第二次实验 实验报告

《数据结构》实验二:     线性表实验

一..实验目的

     巩固线性表的数据结构,学会线性表的应用。

1.回顾线性表的逻辑结构,线性表的物理存储结构和常见操作。

2.学习运用线性表的知识来解决实际问题。

3.进一步巩固程序调试方法。

4.进一步巩固模板程序设计。

二.实验时间

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

三..实验内容

1.建立一个N个学生成绩的顺序表,对表进行插入、删除、查找等操作。分别输出结果。

要求如下:

1)用顺序表来实现。

2)用单链表来实现。

2.解决约瑟夫问题

    设有编号为1,2,3,n的n(n>0)个人围在一起,每人持有一个密码m,从第一个人开始报数,报到m时停止报数,报m的人出圈,再从下一个人开始重新报数,报到m时停止报数,报m的人出圈,……直到的所有人出圈为止。当给定n和m后,输出出圈的次序。

要求如下:自定义数据结构,确定存储方法,并设计算法。在主程序中输入n和m后,输出结果。

3.实现两个集合的相等判定、并、交和差运算。要求:

  1)自定义数据结构

  2)自先存储结构,并设计算法。在VC中实现。

以上三题,第1题必须完成。第2和第3题可以作为选做题。

头文件:

#ifndef Student_H
#define Student_H
const int MaxSize = 10;
class Student
{
public:
	Student()
	{length=0;}
	Student(int a[],int n);
	~Student()
	{}
	void Insert(int i,int x);
	int Delete(int i);
	int Locate(int x);
	void PrintList();
private:
	int data[MaxSize];
	int length;
};
#endif

源文件student.cpp:

#include<iostream>
using namespace std;
#include "Student.h"


Student::Student(int a[],int n)
{
	if(n>MaxSize) throw "参数非法";
	for(int i = 0;i < n;i++)
		data[i] = a[i];
	length = n;
}
void Student::Insert(int i,int x)
{
	if(length>=MaxSize) throw "上溢";
	if(i<1||i>length+1) throw "位置非法";
	for(int j = length;j>=i;j--)
		data[j]=data[j-1];
	data[j-1]=x;
	length++;
}
int Student::Delete(int i)
{
	if(length==0) throw "下溢";
	if(i<1||i>length) throw "位置非法";
	int x = data[i-1];
	for(int j=i;j<length;j++)
		data[j-1]=data[j];
	length--;
	return x;
}


int Student::Locate(int x)
{
	for(int i=0;i<length;i++)
	if(data[i]==x)
		return i+1;
	return 0;
}


void SeqList::PrintList()
{
	for(int i=0;i<length;i++)
		cout<<data[i]<<" ";
	cout<<endl;
}

源文件:Student_main.cpp

<pre name="code" class="cpp">#include <iostream>
using namespace std;
#include "Student.h"

int main()
{
	int r[5]={1,2,3,4,5};
	Student L(r,5);
	cout<<"执行插入操作前的数据为:"<<endl;
	L.PrintLIst();
	try
	{
		L.Insert(2,3);
	}
	catch (char * s)
	{
		cout<<s<<endl;
	}
	cout<<"执行插入操作后的数据位:"<<endl;
	L.PrintList();
	cout<<"值为3的元素位置是:"<<endl;
	cout<<L.Locate(3)<<endl;
	cout<<"执行删除第一个元素操作,删除前数据为:"<<endl;
	L.PrintList();
	try
	{
		L.Delete(1);

	}
	catch(char*s)
	{
		cout<<s<<endl;
	}
	cout<<"删除后的数据位:"<<endl;
	L.Printlist();

}


 

约瑟夫问题:

#include<iostream>
usingnamespacestd;
main()
{
boola[101]={0};
intn,m,i,f=0,t=0,s=0;
cin>>n>>m;
do
{
++t;//逐个枚举圈中的所有位置
if(t>n)
t=1;//数组模拟环状,最后一个与第一个相连
if(!a[t])
s++;//第t个位置上有人则报数
if(s==m)//当前报的数是m
{
s=0;//计数器清零
cout<<t<<'';//输出出局者编号
a[t]=1;//此处人已出局,设置为空
f++;//出局人数+1
}
}while(f!=n);//直到所有人出局为止
}




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值