C语言 - 线性表 所有基本操作
#include
#define MAXSIZE 100
typedef char ElemType;
typedef struct
{
ElemType elem[MAXSIZE];
int length;
}SqList;
SqList L;
//初始化线性表
void InitList_Sq(SqList * L)
{
L->length = 0;//初始化线性表的长度为 0
}
//添加数据
void ListAdd_Sq(SqList * L,ElemType e)
{
int n = L->length;//长度赋值给 n
L->elem[n] = e;//需要添加的数据元素, 放入数组的最后一个位置
++L->length;//添加数据元素后, 线性表的数据长度自增 1
}
//插入数据
int ListInsert_Sq(SqList * L,int i,ElemType e)
{
int j;
if(i<1 || i>L->length+1)//判断是否在数据范围内
return 0;
if(L->length == MAXSIZE)//如果长度达到 MAXSIZE, 则无法继续插入数据
return 0;
for(j=L->length-1; j>=i-1; j--)//从最后一个数据元素开始, 依次向后移动, 形成新的线性表
{
L->elem[j+1] = L->elem[j];
}
L->elem[i-1] = e;//将需要插入的数据元素 e 插入到第 i 的位置
++L->length;//添加数据元素后, 线性表的数据长度自增 1
return 1;
}
//删除数据
int ListDelete_Sq(SqList * L, int i, ElemType * e)
{
int j;
if((i<1) || (i>L->length))//判断需要删除的数据元素的位置是不是在线性表中
return 0;
*e = L->elem[i-1];//将需要删除的数据元素存入变量 e 中
for(j=i; j<=L->length-1; j++)//从第 i 个开始到最后一个结束依次向前移动
{
L->elem[j-1] = L->elem[j];
}
--L->length;//删除数据元素后, 线性表的数据长度自减 1
return 1;
}
//查找数据
int LocateElem_Sq(SqList * L, ElemType e)
{
int i;
for(i=0; ilength; i++)//在线性表中,遍历查找与 e 相同的数据
{
if(L->elem[i] == e)
return i+1;//坐标最终加一为确定位置
}
return 0;
}
//获取线性表中的一个数据元素
ElemType GetElem_Sq(SqList * L, int i)
{
ElemType elem = L->elem[i];//在线性表中,遍历查找数据,相同返回 elem
returnelem;
}
//输出线性表
void display_Sq(SqList * L)
{
int i;
for(i=0; ilength; i++)
{
ElemType e = GetElem_Sq(L,i);//获取线性表中的某一数据后,赋值给 e
printf("%c\n",e);
}
printf("\n");
}
//互换数据
void Exchange_Sq(SqList * L, ElemType a, ElemType b)
{
if(LocateElem_Sq(L, a)-1 <= LocateElem_Sq(L, b)-1)
{
L->elem[L->length] = L->elem[LocateElem_Sq(L, b)-1];
L->elem[LocateElem_Sq(L, b)-1] = L->elem[LocateElem_Sq(L, a)-1];
L->elem[LocateElem_Sq(L, a)-1] = L->elem[L->length];
}
else
{
L->elem[L->length] = L->elem[LocateElem_Sq(L, a)-1];
L->elem[LocateElem_Sq(L, a)-1] = L->elem[LocateElem_Sq(L, b)-1];
L->elem[LocateElem_Sq(L, b)-1] = L->elem[L->length];
}
}
main()
{
int i;
ElemType e;
InitList_Sq(&L);//初始化线性表
//--------------------------------------------------//添加数据
ListAdd_Sq(&L, 'a');
ListAdd_Sq(&L, 'b');
ListAdd_Sq(&L, 'c');
printf("线性表中的内容:\n");
display_Sq(&L);//输出线性表, 形参有输出函数
ListInsert_Sq(&L, 2, 'e');//插入数据,在第二个数据元素前添加字母 e
printf("插入操作后线性表中的内容:\n");
display_Sq(&L);
if(ListDelete_Sq(&L,2,&e) == 1)//删除数据, 删除线性表中第二个数据元素, 并且指向地址 e 保存起来
printf("删除的内容为:%c\n\n", e);
printf("删除操作后的线性表中的内容:\n");
display_Sq(&L);//显示输出, 删除数据后线性表的所有数据
i=LocateElem_Sq(&L, 'a');//查找数据, 查找线性表中字母 a 的位置
if(i == 0)
printf("要查找的数据元素不存在\n\n");
else
printf("要查找的数据元素在%d个\n\n",i);
printf("添加操作后的线性表中的内容:\n");
ListAdd_Sq(&L,'d');//添加数据, 在线性表最后添加字母 d
display_Sq(&L);
printf("互换操作后的线性表中的内容:\n");//互换数据, 将线性表中字母 a 和字母 d 互换
Exchange_Sq(&L, 'a', 'd');
display_Sq(&L);
}