51,714
社区成员




#include <stdio.h>
#include <malloc.h>
#define Maxsize 50
typedef struct
{
char date[Maxsize];//数组即为线性表
int length;
}Sqlist;
//创建新的线性表
void createlist(Sqlist *&L,char a[], int n)
{
L=(Sqlist *)malloc(sizeof(Sqlist));
for(int i=0; i<n; i++)
L->date[i]=a[i];
L->length=n;
}
//初始化
void InitList(Sqlist *&L)
{
L=(Sqlist *)malloc(sizeof(Sqlist));
L->length=0;
}
//插入元素
bool ListInsert(Sqlist *&L,int i,char e)
{
if(i<1 || i>L->length+1) return false;
i--;
for(int j=L->length; j>i; j--)
{
L->date[j]=L->date[j-1];//集体往后移动一位
}
L->date[i]=e;
L->length++;
return true;
}
//输出
void DispList(Sqlist *L)
{
for(int i=0; i<L->length; i++)
{
printf("%c ",L->date[i]);
}
printf("\n");
}
int ListLength(Sqlist *L)
{
return (L->length);
}
bool ListEmpty(Sqlist *L)
{
return (L->length==0);
}
bool GetElem(Sqlist *L, int i, char &e)
{
if(i<1 || i>L->length) return false;
e=L->date[i-1];
return true;
}
//定位该元素在线性表位置
int LocateElem(Sqlist *L,char e)
{
int i=0;
while(i<L->length && L->date[i]!=e) i++;
if(i>=L->length) return 0;
else return i+1;
}
//删除元素
bool ListDelete(Sqlist *L,int i,char &e)
{
if(i<1||i>L->length) return false;
i--;
e=L->date[i];
for(int j=i; j<L->length-1; j++)
L->date[j]=L->date[j+1];//集体前移
L->length--;
return true;
}
void DestoryList(Sqlist *L)
{
free(L);
}
int main()
{
Sqlist *L;
char e;
printf("顺序表的基本运算如下:\n");
printf(" (1)初始化顺序表L\n");
InitList(L);
printf(" (2)依次插入a,b,c,d,e元素\n");
ListInsert(L,1,'a');
ListInsert(L,2,'b');
ListInsert(L,3,'c');
ListInsert(L,4,'d');
ListInsert(L,5,'e');
printf(" (3)输出顺序表L:"); DispList(L);
printf(" (4)顺序表L长度:%d\n",ListLength(L));
printf(" (5)顺序表L为%s\n",(ListEmpty(L)?"空":"非空"));
GetElem(L,3,e);
printf(" (6)顺序表L的第3个元素:%c\n",e);
printf(" (7)元素a的位置:%d\n",LocateElem(L,'a'));
printf(" (8)在第4个位置上插入f元素\n");
ListInsert(L,4,'f');
printf(" (9)输出顺序表L:"); DispList(L);
printf(" (10)删除L的第3个元素\n");
ListDelete(L,3,e);
printf(" (11)输出顺序表L:"); DispList(L);
printf(" (12)释放顺序表L\n");
DestoryList(L);
return 0;
}