順序表基本操作的實現,主要包括順序表的初始化、建立、輸出、插入、刪除、位置查詢、數據查詢。
#include<iostream.h>
#define MAXSIZE 100
typedef int elemtype;
typedef struct
{
elemtype *data;
int length;
}SequenList; //后面的逗號一定不能省略,這是初學者很容易犯的錯誤
這一段是對結構體的定義,此處省略了struct后面的結構體名稱,這是因為在大括號里沒有指向本類型的指針。
//順序表的初始化
void Init_SequenList(SequenList &L)
{
L.data=new elemtype[MAXSIZE]; //申請分配內存空間
if(!L.data)
cout<<"空間分配失敗!\n";
else
{
cout<<"空間分配成功!\n";
L.length=0;
}
}
//順序表的建立
void Creat_SequenList(SequenList &L)
{
cout<<"順序表建立成功\n請輸入表長:";
cin>>L.length;
cout<<"表中元素為:";
for(int i=0;i<L.length;i++)
cin>>L.data[i]; //這里比較容易出現錯誤,要記得后面的一維數組
}
//順序表的輸出
void Print_SequenList(SequenList &L)
{
for(int i=0;i<L.length;i++)
{
cout<<L.data[i]<<'\t';
}
cout<<endl;
}
//順序表數據的插入
void Insert_SequenList(SequenList &L,int i,elemtype x)
{
if(i<0||i>L.length)
cout<<"位置不合理"<<endl;
else
if(L.length==MAXSIZE)
cout<<"表滿"<<endl;
else
{
for(int j=L.length-1;j>=i;j--)
L.data[j+1]=L.data[j]; //這里不大好理解,可以畫圖理解
L.data[i]=x;
L.length++;
}
Print_SequenList(L);
}
//順序表數據的刪除
void Delete_SequenList(SequenList &L,int i)
{
if(i<0||i>L.length-1)
cout<<"位置不合理"<<endl;
else
if(L.length==0)
cout<<"空表"<<endl;
else
{
for(int j=i+1;j<L.length;j++)
L.data[j-1]=L.data[j];
L.length--;
}
Print_SequenList(L);
}
//順序表對數據的位置尋找
void Getelem_SequenList(SequenList &L,int i,elemtype &e)
{
if(i<0||i>L.length-1)
cout<<"查找的位置不存在"<<endl;
else
{
e=L.data[i];
cout<<e<<endl;
}
}
//順序表對數據的查找
int Search_SequenList(SequenList &L,elemtype e)
{
for(int i=0;i<L.length;i++)
if(L.data[i]==e)
return i+1;
return 0;
}
main函數的實現
void main()
{
SequenList L;
Init_SequenList(L);
Creat_SequenList(L);
Print_SequenList(L);
int i;
elemtype x;
cout<<"請輸入插入的位置和元素:";
cin>>i>>x;
Insert_SequenList(L,i,x);
cout<<"請輸入刪除的位置:";
cin>>i;
Delete_SequenList(L,i);
elemtype e;
cout<<"請輸入查找的位置:";
cin>>i;
Getelem_SequenList(L,i,e);
cout<<"請輸入查找的元素:";
cin>>e;
if(!Search_SequenList(L,e))
cout<<"輸入的元素"<<e<<"不在順序表中"<<endl;
else
cout<<"輸入的元素"<<e<<"在順序表的第"<<Search_SequenList(L,e)<<"位中"<<endl;
}
值得注意的是,有一定C/C++基礎的同學可以復習一下指針的知識,會給你帶來驚喜哦!