資料結構-順序表驗證實驗
阿新 • • 發佈:2018-12-08
SeqList.h
#ifndef SeqList_H
#define SeqList_H
const int MaxSize=18;class SeqList
{
public:
SeqList(){length=0;}
SeqList(int a[],int n);
~SeqList(){}
void Insert(int i,int x);
int Delete(int i);
int Locate(int x);
void PrintList();
private:
int data[MaxSize];
};
#endif
SeqList.cpp
#include<iostream>
using namespace std;#include "SepList.h"
SeqList::SeqList(int a[],int n)
{
if(n>MaxSize)throw"非法";
for(int i=0;i<n;i++)
data[i]=a[i];
length=n;
}
void SeqList::Insert(int i,int x)
{
if(length>=MaxSize)throw"上溢";
for(int j=length;j>=1;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"illegal";
int x=data[i-1];
for(int j=i;j<length;j++)
length--;
return x;
}
int SeqList::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;
}
SeqList.main.cpp
#include<iostream>
using namespace std;
#include "SepList.h"
void main()
{
int r[5]={1,2,3,4,5};
SeqList L(r,5);
cout<<"執行插入操作前資料為:"<<endl;
L.PrintList();
try
{
L.Insert(2,3);
}
catch(char *s)
{
cout<<s<<endl;
}
cout<<"執行插入操作後的資料為:"<<endl;
L.PrintList();
cout<<"值為3的元素位置為:";
cout<<L.Locate(3)<<endl;
cout<<"執行刪除第一個元素操作,刪除前資料為:"<<endl;
L.PrintList();
try
{
L.Delete(1);
}
catch(char *s)
{
cout<<s<<endl;
}
cout<<"刪除後資料為:"<<endl;
L.PrintList();
}