1 #include<stdio.h>
2 #define MAXSIZE 20
3
4 typedef int ElemType;
5 typedef struct
6 {
7 ElemType data[MAXSIZE];
8 int length;
9 }SqList;
10
11 void InitList(SqList *L)
12 {
13 L->length=5;
14 int i;
15 for(i=0;i<5;i++)
16 {
17 L->data[i]=i+1;
18 }
19 return;
20 }
21 int ListLength(SqList L)
22 {
23 return L.length;
24 }
25 bool ListEmpty(SqList L)
26 {
27 if(L.length==0)return false;
28 else return true;
29 }
30
31 void ClearList(SqList *L)
32 {
33 L->length=0;
34 return;
35 }
36
37 bool GetElem(SqList L,int i,int *e)
38 {
39 if(i==0||i>L.length||L.length==0)return false;
40 else
41 {
42 *e=L.data[i-1];
43 return true;
44 }
45 }
46 int LocateElem(SqList L,int e)
47 {
48 int i;
49 if(L.length==0)return 0;
50 else{
51 for(i=0;i<L.length;i++)
52 {
53 if(L.data[i]==e)
54 {
55 return i+1;
56 break;
57 }
58 else if(i==L.length-1&&L.data[L.length-1]!=e)
59 {
60 return 0;
61 break;
62 }
63 }}
64 }
65 bool ListInsert(SqList *L,int i,int e)
66 {
67 if(i<=0||i>L->length+1||L->length==MAXSIZE)return false;
68 else {
69 //插入数据位置不在表尾
70 if(i<=L->length){
71 int k;
72 for(k=L->length-1;k>=i-1;k--)
73 {
74 L->data[k+1]=L->data[k];
75 }}
76 L->data[i-1]=e;
77 L->length++;
78 return true;
79 }
80 }
81 void PrintList(SqList L)
82 {
83 int i;
84 for(i=0;i<L.length;i++)
85 {
86 printf("%d ",L.data[i]);
87 }
88 printf("
");
89 return;
90 }
91 bool ListDelete(SqList *L,int i,int *e)
92 {
93 if(L->length==0||i<=0||i>L->length)return false;
94 else
95 {
96 *e=L->data[i-1];
97 if(i<L->length)//删除位置不在表尾
98 {
99 int k;
100 for(k=i;k<L->length;k++)
101 {
102 L->data[k-1]=L->data[k];
103 }
104 }
105 L->length--;
106 return true;
107 }
108
109 }
110 int main()
111 {
112 SqList L;
113 //初始化
114 InitList(&L);
115 //判断是否为空
116 if(ListEmpty(L))printf("非空
");
117 else printf("空
");
118 //读取顺序表中元素个数
119 printf("顺序表中元素个数为%d
",ListLength(L));
120 //读取
121 int i,e;
122 printf("请输入您要读取的数字序号:");
123 scanf("%d",&i);
124 if(GetElem(L,i,&e))
125 printf("第%d个元素是%d
",i,e);
126 else if(!GetElem(L,i,&e))
127 printf("发生错误请重新输入
");
128 //查找
129 printf("请输入您要查找的数字:");
130 scanf("%d",&e);
131 if(LocateElem(L,e)!=0)printf("您查找的数字序号为%d
",LocateElem(L,e));
132 else printf("您查找的数字不存在
");
133 //插入
134 printf("请输入您要插入的数字:");
135 scanf("%d",&e);
136 printf("请输入您要插入的位置:");
137 scanf("%d",&i);
138 ListInsert(&L,i,e);
139 printf("插入后的顺序表如下:
");
140 PrintList(L);
141 //删除
142 printf("请输入您要删除的数字位置:");
143 scanf("%d",&i);
144 ListDelete(&L,i,&e);
145 printf("您删除的数字为%d
",e);
146 printf("删除后的顺序表如下:
");
147 PrintList(L);
148 //清空
149 ClearList(&L);
150 //判断是否为空
151 if(ListEmpty(L))printf("非空
");
152 else printf("空
");
153 return 0;
154 }