顺序表的基本操作

2025-04-30 07:33:10
推荐回答(1个)
回答1:

#define LIST_INTSIZE 50
typedef char DataType;
typedef struct
{
DataType* elem; //顺序表的基地址
int length; //顺序表当前长度
int listsize; //顺序表当前分配的存储容量
}SeqList;
int InitSeqList(SeqList* L) //初始化顺序表
{
L->elem=(DataType *)malloc((LIST_INTSIZE+1)*sizeof(DataType));
if (L->elem==NULL)
{
cout<<"\t\t\t内存分配错误\n";
return 0;
}
L->length=0;
L->listsize=LIST_INTSIZE;
cout<<"\t\t\t内存分配成功";
return 1;
}
int InsertSeqList(SeqList* L,int i,DataType x) //对顺序表进行插入操作,插入格式如(1,a)
{
int j;
if (L->length==L->listsize)
{
cout<<"\t\t\t顺序表已满";
return 0;
}
else
{
if (i<1||i>L->length+1)
{
cout<<"\t\t\t位置不合法";
return 0;
}
else
{
for(j=L->length;j>=i;j--)
{
L->elem[j+1]=L->elem[j];
}
L->elem[i]=x;
L->length++;
return 1;
}
}
}
int DeleteSeqList(SeqList* L,int i) //对顺序表进行删除操作
{
int j;
if (i<1||i>L->length)
{
cout<<"\t\t\t不存在第i个元素";
return 0;
}
else
{
for (j=i;jlength;j++)
{
L->elem[j]=L->elem[j+1];
}
L->length--;
return 1;
}
}
int LenSeqList(SeqList* L) //求顺序表表长
{
int n=0;
int i=1;
for (i=1;i<=L->length;i++)
{
n++;
}
return n;
}
int SearchSeqList(SeqList* L,DataType x) //按值查找
{
int j=1;
while (j<=L->length && L->elem[j]!=x)
j++;
if(j>L->length)
{
cout<<"\t\t\t找不到你要的值,请重新输入";
return (0);
}
else
return j;
}
DataType GetfromSeqList(SeqList* L,int i) //按位置查找
{
DataType x;
if(i<1||i>L->length)
{
cout<<"\t\t\t查找位置不合法";
return 0;
}
else
{
x=L->elem[i];
return x;
}
}
void ShowSeqList(SeqList* L) //显示顺序表
{
int i;
cout<<"\n\t\t\t显示线性表的所有元素: ";
if (L->length==0)
{
cout<<"\n\t\t\t链表为空";
}
else
{
cout<<"\n\t\t\t");
for(i=1;i<=L->length;i++)
{
cout<<"\t",L->elem[i];
}
}
}