|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #include<stdio.h>
- #include<malloc.h>
- #include<stdlib.h>
- #define maxsize 100 //定义顺序表的最大储存个数是100
- typedef int ElemType;
- //定义顺序表的结构,并用ElemType的数组来储存数组元素,并且元素的个数为length
- typedef struct
- {
- ElemType data[maxsize];
- int length;
- }List;
- //建立顺序表(定义一个函数建立顺序表,将数组a的元素给顺序表)
- void creatList(List*& L, ElemType a[], int n)
- {
- int length = 0;
- L = (List*)malloc(sizeof(List));
- for (int i = 0; i < n; i++)
- {
- L->data[i] = a[i];
- length += 1;
- }
- L->length = length;
- }
- //初始化顺序表
- void initList(List*& L)
- {
- L = (List*)malloc(sizeof(List)); //给顺序表L分配空间
- L->length = 0; //定义L的长度length为0
- }
- //销毁顺序表
- void destroyList(List*& L)
- {
- free(L); //释放顺序表L的空间
- }
- //判断顺序表是否为空
- bool listEmpty(List*& L)
- {
- return(L->length == 0); //若为空,返回true,如果不为空,返回false
- }
- //求线性表的长度
- int ListLength(List*& L)
- {
- return (L->length);
- }
- //输出线性表
- void outputList(List*& L)
- {
- if (listEmpty(L)) //如果顺序表为空
- {
- printf("顺序表为空!\n");
- return;
- }
- else //否则逐个输出元素
- {
- for (int i = 0; i < L->length; i++)
- {
- printf("%d ", L->data[i]);
- }
- printf("\n");
- }
- }
- //取顺序表中某个位置的元素
- void GetElem(List*& L, int i, int& e) //在线性表L中取第i位置的值并给e
- {
- if (i < 0 || i > L->length || L->length == 0) //如果i不合法或者L为空
- {
- printf("顺序表为空!\n");
- return;
- }
- else
- {
- e = L->data[i-1];
- }
- }
- //判断顺序表中是否存在某个元素,并返回所在位置
- void LocateElem(List*& L, ElemType e)
- {
- for (int i = 0; i < L->length; i++)
- {
- if (e == L->data[i])
- {
- printf("位置在%d处\n", i + 1);
- return;
- }
- }
- }
- //插入元素(在线性表的第i个位置插入元素e)
- void ListInsert(List*& L, int i, ElemType e)
- {
- if (i<0 || i>L->length + 1) //如果i不合法
- {
- printf("输入位置不合法!\n");
- return;
- }
- else
- {
- for (int j = L->length-1; j >= i-1; j--)
- {
- L->data[j + 1] = L->data[j];
- }
- L->data[i - 1] = e;
- L->length += 1;
- }
- }
- //删除元素
- void ListDelete(List*& L, int i) //在顺序表中删除第i个元素
- {
- if (i<0 || i>L->length)
- {
- printf("删除位置不合法!\n");
- return;
- }
- else
- {
- for (int j = i-1; j < L->length; j++)
- {
- L->data[j] = L->data[j + 1];
- }
- L->length -= 1;
- }
- }
- int main()
- {
- List *L;
- int e=99;
- int a[4] = { 0,1,2,3 };
- creatList(L, a, 4);
- //initList(L);
- outputList(L);
- printf("该顺序表的长度是%d\n", ListLength(L));
- //取线性表某个位置的值
- GetElem(L, 1, e);
- printf("取出来的值是:%d\n", e);
- //判断是否有某个元素
- LocateElem(L, 1);
- //插入
- ListInsert(L, 10, 100);
- ListInsert(L, 2, 100);
- outputList(L);
- //删除
- ListDelete(L, 1);
- outputList(L);
- //销毁
- destroyList(L);
- outputList(L);
-
- return 0;
- }
复制代码
|
|