实验目的:掌握线性表的顺序存储结构;验证顺序表及其基本操作的实现。
主要内容:建立含有若干个元素的顺序表;对已建立的顺序表实现插入、删除、查找等基本操作;设计一个测试主函数验证所设计的算法。
(1)建立顺序表
typedef int DataType;
typedef struct
{
DataType list[MaxSize];
int length;
}SeqList;
(2)初始化
void ListInitiate(SeqList* L)
{
L->length = 0;
}
(3)插入
int Sqlist_insert(SeqList *L, int i, DataType x)
{
int j;
if (L->length >= MaxSize)
return 0;
else if (i<1 || i>L->length + 1)
return 0;
else
{
for (j = L->length; j >= i; j--)
L->list[j] = L->list[j - 1];
L->list[i - 1] = x;
L->length++;
return 1;
}
(4)删除
int ListDelete(SeqList* L, int i, DataType* x)
{
int j;
if (L->length == 0)
return 0;
else if (i<1 || i>L->length )
return 0;
else
{
*x = L->list[i - 1];
for (j = i; j < L->length; j++)
L->list[j-1] = L->list[j];
L->length--;
return 1;
}
}
(5)按值查找
int ListGet(SeqList L, int i, DataType* e)
{
if (i<1 || i>L.length)
return 0;
else
{
*e = L.list[i - 1];
return 1;
}
}
全部代码实现:
#include<stdio.h>
#define MaxSize 100
typedef int DataType;
typedef struct
{
DataType list[MaxSize];
int length;
}SeqList;
int i, x;
void ListInitiate(SeqList* L)
{
L->length = 0;
}
int Sqlist_insert(SeqList *L, int i, DataType x)
{
int j;
if (L->length >= MaxSize)
return 0;
else if (i<1 || i>L->length + 1)
return 0;
else
{
for (j = L->length; j >= i; j--)
L->list[j] = L->list[j - 1];
L->list[i - 1] = x;
L->length++;
return 1;
}
}
int ListDelete(SeqList* L, int i, DataType* x)
{
int j;
if (L->length == 0)
return 0;
else if (i<1 || i>L->length )
return 0;
else
{
*x = L->list[i - 1];
for (j = i; j < L->length; j++)
L->list[j-1] = L->list[j];
L->length--;
return 1;
}
}
int ListGet(SeqList L, int i, DataType* e)
{
if (i<1 || i>L.length)
return 0;
else
{
*e = L.list[i - 1];
return 1;
}
}
void ListShow(SeqList L)
{
int i;
printf("顺序表为:\n");
for (i = 0; i < L.length; i++)
{
printf("%3d", L.list[i]);
}
printf("\n");
}
#include<stdio.h>
#define MaxSize 100
#define MaxLen 10
typedef int DataType;
#include"SeqList.h";
int main()
{
SeqList L;
int i, x,e;
ListInitiate(&L);
Sqlist_insert(&L, 1, 21);
Sqlist_insert(&L, 2, 31);
Sqlist_insert(&L, 3, 32);
Sqlist_insert(&L, 4, 41);
Sqlist_insert(&L, 5, 51);
Sqlist_insert(&L, 6, 11);
Sqlist_insert(&L, 7, 44);
Sqlist_insert(&L, 8, 56);
Sqlist_insert(&L, 9, 78);
Sqlist_insert(&L, 10, 90);
ListShow(L);
for (i = 0; i < MaxLen; i++);
{
ListGet(L, 4, &e);
printf("%d \n", e);
}
ListDelete(&L, 4, &x);
ListShow(L);
return 0;
}
运行结果: