1 //顺序表运算算法
 2 #include <stdio.h>
 3 #include <malloc.h>
 4 #include <iostream>
 5 #define MaxSize 50
 6 typedef char ElemType; 
 7 typedef struct 
 8 {    ElemType data[MaxSize];        //存放顺序表元素
 9        int length;                    //存放顺序表的长度
10 } SqList;                        //声明顺序表的类型
11 void CreateList(SqList *&L,ElemType a[],int n) //整体建立顺序表
12 {
13     L=(SqList *)malloc(sizeof(SqList));
14     for (int i=0;i<n;i++)
15         L->data[i]=a[i];
16     L->length=n;
17 }
18 void InitList(SqList *L)    //初始化线性表
19 {
20     // L=(SqList *)malloc(sizeof(SqList));    //分配存放线性表的空间
21     L->length=0;
22 }
23 void DestroyList(SqList *&L)  //销毁线性表
24 {
25     free(L);
26 }
27 bool ListEmpty(SqList *L)    //判线性表是否为空表
28 {
29     return(L->length==0);
30 }
31 int ListLength(SqList *L)    //求线性表的长度
32 {
33     return(L->length);
34 }
35 void DispList(SqList *L)    //输出线性表
36 {
37     for (int i=0;i<L->length;i++)
38         printf("%c ",L->data[i]);
39     printf("\n");
40 }
41 bool GetElem(SqList *L,int i,ElemType &e)    //求线性表中第i个元素值
42 {
43     if (i<1 || i>L->length)
44         return false;
45     e=L->data[i-1];
46     return true;
47 }
48 int LocateElem(SqList *L, ElemType e)    //查找第一个值域为e的元素序号
49 {
50     int i=0;
51     while (i<L->length && L->data[i]!=e) i++;
52     if (i>=L->length)
53         return 0;
54     else
55         return i+1;
56 }
57 bool ListInsert(SqList *&L,int i,ElemType e)    //插入第i个元素
58 {
59     int j;
60     if (i<1 || i>L->length+1)
61         return false;
62     i--;                        //将顺序表位序转化为elem下标
63     for (j=L->length;j>i;j--)     //将data[i]及后面元素后移一个位置
64         L->data[j]=L->data[j-1];
65     L->data[i]=e;
66     L->length++;                //顺序表长度增1
67     return true;
68 }
69 bool ListDelete(SqList *&L,int i,ElemType &e)    //删除第i个元素
70 {
71     int j;
72     if (i<1 || i>L->length)
73         return false;
74     i--;                        //将顺序表位序转化为elem下标
75     e=L->data[i];
76     for (j=i;j<L->length-1;j++)    //将data[i]之后的元素前移一个位置
77         L->data[j]=L->data[j+1];
78     L->length--;                //顺序表长度减1
79     return true;
80 }
81 int main() {
82     SqList *L;//创建指针的空间,并不对结构体L创建空间
83     L=(SqList *)malloc(sizeof(SqList));//需要创建空间
84     ElemType e;
85     InitList(L);
86     char list[]={'a','b','c','d'};
87     // ListInsert(L,L->length-1,'A');
88     CreateList(L,list,4);
89     // InitList(L);
90     // ListInsert(L,L->length,'A');
91     printf("%d\n",L->length);
92     ListInsert(L,1,'A');
93     printf("%d\n",L->length);
94     DispList(L);
95     printf("%c",L->data[0]);
96 }

 

posted on 2020-10-17 09:44  --琛琛--  阅读(132)  评论(0)    收藏  举报