69,382
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<malloc.h>
#define MaxSize 50
typedef char ElemType;
typedef struct{
ElemType data[MaxSize];
int length;
}SqList;
void InitList(SqList * &L){//初始化顺序表
L=(SqList *)malloc(sizeof(SqList));//分配存放线性表的空间
L->length=0;//置空线性表长度为0
}
void CreateList(SqList *&L,ElemType a[],int n)
{
int i;
L=(SqList *)malloc(sizeof(SqList));
for(i=0;i<n;i++)
L->data[i]=a[i];
L->length=n;
}
void DestroyList(SqList *L){
free(L);
}
bool ListEmpty(SqList *L){//判断线性表是否为空表
return (L->length==0);
}
int ListLength(SqList *L){//输出线性表的长度
return(L->length);
}
void DispList(SqList *L)//输出线性表
{
int i;
if(ListEmpty(L))
return;
for(i=0;i<L->length;i++)
printf("%c",L->data[i]);
printf("\n");
}
bool GetElem(SqList *L,int i,ElemType &e)//求线性表某个数据的元素值
{
if(i<1||i>L->length)
return false;
e=L->data[i-1];
return true;
}
int LocateElem(SqList *L,ElemType e){
int i=0;
while(i<L->length && L->data[i]!=e)
i++;
if(i>=L->length)
return 0;
else
return i+1;
}
bool ListInsert(SqList *L,int i,ElemType e)
{
int j;
if(i<1||i>L->length+1)
return false;
i--;
for(j=L->length;j>i;j--)
L->data[i]=e;
L->length++;
return true;
}
bool ListDelete(SqList *&L,int i,ElemType &e)
{
int j;
if(i<1 || i> L-> length)
return false;
i--;
e=L->data[i];
for(j=i;j<L->length-1;j++)
L->data[j]=L->data[j+1];
L->length--;
return true;
}
int main()
{//从键盘得到数组元素
int n;
char a[100];
SqList *L;
ElemType e;
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%c",&a[i]);
CreateList(L,a,n);
DispList(L);
printf("%d\n",ListLength(L));
printf("%s\n",(ListEmpty(L)?"no":"yes"));
GetElem(L,3,e);
printf("%c\n",e);
printf("%d\n",LocateElem(L,'a'));
ListInsert(L,4,'f');
DispList(L);
ListDelete(L,3,e);
DispList(L);
DestroyList(L);
}
bool ListInsert(SqList *L,int i,ElemType e)
{
int j;
if(i<1||i>L->length+1)
return false;
i--;
for(j=L->length;j>i;j--)
L->data[j]=L->data[j-1];
L->data[i]=e;
L->length++;
return true;
}