实现顺序表的各种基本运算和整体建表算法(设顺序表的元素类型elemtype 为 char),完成如下功能:
1.初始化顺序表L;
2.依次插入abcde元素;
3.输出顺序表L;
4.输出顺序表L的长度;
5.判断顺序表L是否为空;
6.输出顺序表L的第三个元素
7.输出元素a的位置
8.在第四个元素位置上插入f元素
9.输出顺序表L
10.删除顺序表L的第三个元素
11.输出顺序表L,释放顺序表L.
#include <stdio.h>
#include<stdlib.h>
#define MaxSize 50
typedef char elemtype;
typedef struct
{
elemtype data[MaxSize];//存放顺序表元素
int length; //存放顺序表的长度
}sqlist;
void create_list(sqlist*& L, elemtype a[], int n)
{
L = (sqlist*)malloc(sizeof(sqlist));
for (int i = 0; i < n; i++)
{
L->data[i] = a[i];
}
L->length = n;
}
void initlist(sqlist*& L)
{
L = (sqlist*)malloc(sizeof(sqlist));
L->length = 0;
}
void destroy_list(sqlist*& L)
{
free(L);
}
bool listempty(sqlist* L)
{
return(L->length == 0);
}
int listlength(sqlist* L)
{
return(L->length);
}
void displist(sqlist* L) //输出线性表
{
for (int i = 0; i < L->length; i++)
{
printf("%c", L->data[i]);
printf("\n");
}
}
bool getelem(sqlist * L, int i, elemtype & e) //求线性表中第i个元素的值
{
if (i<1 || i>L->length)
{
return false;
}
else
{
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) //插入第i个元素
{
int j;
if (i<1 || i>L->length + 1 || L->length == MaxSize)
{
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;
}
bool deletelist(sqlist*& L, int i,elemtype &e ) //删除第i个元素
{
int j;
if (L->length == 0 || i<1 || i>L->length)
{
return false;
}
i--;
e = L->data[i];
for (j = i; j < L->length - 1; j++)
{
L->data[i] = L->data[i + 1];
}
L->length--;
return true;
}
int main()
{
sqlist* L;
elemtype e;
printf("顺序表的基本运算如下:\n");
printf("(1)初始化线性表");
initlist(L);
printf("依次插入abcde元素\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)顺序表为%s\n", (listempty(L) ? "空" : "非空"));
getelem(L, 3, e);
printf("(6)顺序表L的第三个元素:%c\n", e);
printf("(7)元素a的位置:%d\n", locateelem(L, 'a'));
printf("(8)在第四个元素位置上插入f元素%c\n");
listinsert(L, 4, 'f');
printf("(9)输出线性表L:");
displist(L);
printf("(10)删除L的第三个元素\n");
deletelist(L,3,e);
printf("(11)输出线性表L:");
displist(L);
printf("(12)释放线性表L:");
destroy_list(L);
return 0;
}
运行结果如下: