typedef int ElemType;
typedef struct
{
ElemType *list;
int len;
int MaxSize;
}ListSq ;
/* 1.初始化線性表,分兩種情況,一種不需分配空間,一種為其分配空間*/
void InitList(ListSq &L)
{
L.list=NULL;
L.len=L.MaxSize=0;
}
void InitList(ListSq &L,int ms)
{
if (ms<0)
{
cout<<"ms值非法"<<endl; exit(1);
}
L.MaxSize=ms;
L.list=new ElemType[L.MaxSize];
if (L.list==NULL)
{
cout<<"記憶體配置失敗"<<endl;exit(1);
}
L.len=0;
}
/* 2.得到線性表中第pos個位置元素的值*/
ElemType GetElemList(ListSq &L,int pos)
{
if (pos<0||pos>L.len)
{
cout<<"所給下標無效"<<endl;exit(1);
}
return L.list[pos];
}
/* 3.從線性表中尋找一個元素,返回該元素的位置,尋找失敗返回-1*/
/*順序尋找,演算法複雜度為O(n)*/
int FindList(ListSq &L,ElemType item)
{
int i;
for (i=0;i<L.len;i++)
{
if (item==L.list[i])
{
return i;
}
}
return -1;
}
/*二分尋找,針對線性表中元素是有序的,即是按照每一關鍵字升序或者降序排列 尋找不成功返回-1 演算法複雜度O(logn)*/
int BinaryFindList(ListSq &L,ElemType item)
{
int low=0;
int high=L.len-1;
while (low<=high)
{
int mid=(low+high)/2;
if (item==L.list[mid])
{
return mid;
}
else if (item<L.list[mid])
{
high=mid-1;
}
else low=mid+1;
}
return -1;
}
/* 4.修改線性表中的第一個指定元素*/
bool ModifyList(ListSq &L,const ElemType & item )
{
int i;
for (i=0;i<L.len;i++)
{
if (item==L.list[i])
{
L.list[i]=item;
return true;
}
}
return false;
}
/* 5.向線性表中插入一個元素 分兩種情況,一種是插入到指定位置,另一種是插入後還是保持原來的有序性*/
void InsertList(ListSq &L,ElemType item,int pos)
{
int i;
if (pos<1||pos>L.len)
{
cout<<"所給插入元素的位置編號無效";
exit(1);
}
if (L.len==L.MaxSize)
{
ElemType *p=new ElemType[2*L.MaxSize+1];
if (p==NULL)
{
cout<<"記憶體非配失敗"<<endl;exit(1);
}
for (i=0;i<L.len;i++)
{
p[i]=L.list[i];
}
delete []L.list;
L.list=p;
L.MaxSize=2*L.MaxSize+1;
}
for (i=L.len;i>=pos;i--)
{
L.list[i]=L.list[i-1];
}
L.list[pos-1]=item;
L.len++;
}
/*有序插入,即在有序線性表插入*/
void OrderInsertList(ListSq &L,ElemType item)
{
int i,j;
if (L.len==L.MaxSize)
{
ElemType *p=new ElemType[2*L.MaxSize+1];
if(p==NULL)
{
cout<<"記憶體配置失敗"<<endl;exit(1);
}
for (i=0;i<L.len;i++)
{
p[i]=L.list[i];
}
delete []L.list;
L.list=p;
L.MaxSize=2*L.MaxSize+1;
}
for (i=0;i<L.len-1;i++)
{
if (item<L.list[i])
{
break;
}
}
for(j=L.len;j>=i+1;j--)
{
L.list[j]=L.list[j-1];
}
L.list[i]=item;
L.len++;
}
/* 6.從線性表中刪除滿足條件的第一個元素*/
bool DeleteList(ListSq & L,ElemType item)
{
int i,j;
for (i=0;i<L.len;i++)
{
if (item==L.list[i])
{
break;
}
}
if (i==L.len)return false;
else
{
for (j=i;j<L.len;j++)
{
L.list[j]=L.list[j+1];
}
L.len--;
return true;
}
}
/* 7.判斷線性表是否為空白*/
bool EmptyList(ListSq &L)
{
return L.len==0;
}
/* 8.求出線性表長度*/
int LenthList(ListSq &L)
{
return L.len;
}
/* 9.遍曆出線性表*/
void OutputList(ListSq &L)
{
for (int i=0;i<L.len;i++)
{
cout<<L.list[i]<<' ';
}
cout<<endl;
}
/* 10.清除線性表中的所有元素,釋放佔有的動態記憶體空間*/
void ClearList(ListSq &L)
{
if (L.list!=NULL)
{
delete []L.list;
L.list=NULL;
L.len=L.MaxSize=0;
}
}