实验二 线性表综合实验——静态链表

一、实验目的

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

二、.实验内容     

建立一个由n个学生成绩的顺序表,n的大小由自己确定,每一个学生的成绩信息由自己确定,实现数据的对表进行插入、删除、查找等操作。分别输出结果。 

三、程序代码 

#include<iostream>
using namespace std;
const int MaxSize=100;
struct Node
{
	int data;
	int next;
}SList[MaxSize];
class LinkList
{
private:
	int first,avail;
public:
	LinkList(int a[],int n);
	~LinkList(){};
	int Locate(int x);
	void Insert(int i,int x);
	int Delete(int i);
	void PrintList();
};

LinkList::LinkList(int a[],int n)
{
	if(n<0||n>MaxSize) 
		throw"参数非法";
	for(int i=0;i<MaxSize;i++)
	{
		SList[i].next=i+1;
	}
	SList[MaxSize-1].next=-1;
	first=0;
	avail=1;
	SList[first].next = -1;
	for(int j=0;j<n;j++)
	{
		int s=avail;
		avail=SList[avail].next;
		SList[s].data=a[j];
		SList[s].next=SList[first].next;
		SList[first].next=s;
	}
}

void LinkList::Insert(int i,int x)
{
	if(i<0||i>MaxSize) 
		throw"参数非法";
	int s=avail;
	int p=first;
	if(p==-1)
		throw"参数非法";
	for(int count=0;count<i-1;count++)
	{
		p=SList[p].next;
	}
	avail=SList[avail].next;
	SList[s].data=x;
	SList[s].next=SList[p].next;
	SList[p].next=s;
}
int LinkList::Delete(int i)
{
	if(i<0||i>MaxSize) 
		throw"参数非法";
	int p=first;
	if(p==-1)
		throw"参数非法";
	for(int count=0;count<i-1;count++)
	{
		p=SList[p].next;
	}
	int q=SList[p].next;
	SList[p].next=SList[q].next;
	SList[q].next=avail;
	avail=q;
	return 0;
}
int LinkList::Locate(int x)
{
	if(SList[first].next==-1)
		throw"成绩为空";
	int p=first,count=0;
	while(SList[p].next!=-1)
	{
		if(SList[p].data==x) return count;
		p=SList[p].next;
		count++;
	}
	return 0;
}
void LinkList::PrintList()
{
	int p=SList[first].next;
	while(p!=-1)
	{
		cout<<SList[p].data<<" ";
		p=SList[p].next;
	}
	cout<<endl;
}
int main()
{
	int r[5]={91,92,94,95,96};
	LinkList L(r,5);
	cout<<"执行插入操作前数据为:"<<endl;
	L.PrintList();
	cout<<"在第四个位置插入成绩93"<<endl;
	try
	{
		L.Insert(4,93);
	}
	catch(char *s)
	{
		cout<<s<<endl;
	}
	cout<<"执行插入操作后数据为:"<<endl;
	L.PrintList();
	cout<<"成绩为93的学生位置为:";
	cout<<L.Locate(93)<<endl;
	cout<<"执行删除操作前数据为:"<<endl;
	L.PrintList();
	cout<<"删除第一个成绩"<<endl;
	try
	{
		L.Delete(1);
	}
	catch(char *s)
	{
		cout<<s<<endl;
	}
	cout<<"执行删除操作后数据为:"<<endl;
	L.PrintList();
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值