1. 程式人生 > >信管117201蔡鴻嶽資料結構實驗一

信管117201蔡鴻嶽資料結構實驗一

#include<iostream>
using namespace std;
int i,j,x;
const int MaxSize=10;
class SeqList
{
	public:
		SeqList(){length=0;}
		SeqList(int a[],int n);
		~SeqList(){}
		int Length(){return length;}
		int Locate(int x);
		void Insert(int i,int x);
		int Delete(int i);
		void PrintList();
	private:
		int data[MaxSize];
		int length;
};

SeqList::SeqList(int a[],int n)
{
	if(n>MaxSize)throw"引數非法";
	for(i=0;i<n;i++)
		data[i]=a[i];
	length=n;
}

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

void SeqList::Insert(int i,int x)
{
	if(length>=MaxSize)throw"上溢";
	if(i<1||i>length+1)throw"位置非法";
	for(j=length;j>=i;j--)
		data[j]=data[j-1];
	data[i-1]=x;
	length++;
}

int SeqList::Delete(int i)
{
	if(length==0)throw"下溢";
	if(i<1||i>length)throw"位置非法";
	x=data[i-1];
	for(j=i;j<length;j++)
		data[j-1]=data[j];
	length--;
	return x;
}

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

void main()
{
	int r[5]={1,2,3,4,5};
	SeqList L(r,5);
	cout<<"執行插入操作前資料為:";
	L.PrintList();
	try
	{
		L.Insert(2,3);
	}
	catch (char *s)
	{
		cout<<endl<<s;
	}
	cout<<endl<<"執行插入操作後資料為:";
	L.PrintList();
	cout<<endl<<"值為3的元素位置為:";
	cout<<L.Locate(3);
	cout<<endl<<"執行刪除第一個元素操作,刪除前資料為:";
	L.PrintList();
	try
	{
		L.Delete(1);
	}
	catch (char *s)
	{
		cout<<endl<<s;
	}
	cout<<endl<<"刪除後資料為:";
	L.PrintList();
}