1. 程式人生 > >順序表用c++實現的例子

順序表用c++實現的例子

#include<iostream>
using namespace std;
#define MAX 100
int n,i,j,x,len;


int SeqList [MAX+1] ;


void Add()//錄入
{


cout<<"How many number you want :"<<endl;
cin>>n;
len=n;
for(i=1;i<=n;i++)
{
cout<<"Please input the No."<<i<<" number:"<<endl;
cin>>SeqList[i];
}
cout<<"The List is"<<endl;
for(i=1;i<=n;i++)
{
cout<<SeqList[i]<<" ";
}
cout<<endl;
}




int Get()//按位查詢
{
cout<<"Please input the search position:";
cin>>i;
if(i<i||i>len) throw "position error";
else cout<<SeqList[i]<<endl;
return 0;
}


int Loc()//按值查詢
{
cout<<"what number' position do you want:";
cin>>x;
for(i=1;i<len;i++)
if(SeqList[i]==x)
{


cout<<"Its position is: "<<i<<endl;
}
return 0;
}


int Insert()
{
int i;
len++;
if(len>MAX) throw "overflow";
cout<<"which position do you want to insert?";
cin>>i;
cout<<"what number will you inser:";
cin>>x;
if(i<1||i>len+1) throw "position";
for(j=len;j>=i;j--)
{
SeqList[j]=SeqList[j-1];
}
SeqList[i]=x;


cout<<"The new list is "<<endl;
for(i=1;i<=len;i++)
{
cout<<SeqList[i]<<" ";
}
cout<<endl;
return 0;
}




int Delete()
{


if(len==0) throw "underflow";
cout<<"which position do you want to delete?";
cin>>i;
if(i<1||i>len) throw "position";
x=SeqList[i];
for(j=i+1;j<=len;j++)
{
SeqList[j-1]=SeqList[j];


}
cout<<"The new list is: ";
len--;
for(i=1;i<=len;i++)
{
cout<<SeqList[i]<<" ";
}
cout<<endl;
return 0;
}










void main()
{
Add();
Get();
Loc();
Insert();
Get();
Loc();
 Delete();
 Get();
Loc();
}