王道23年代码练习(1)顺序表插入删除

1 #include <stdio.h>
 2 #include <malloc.h>
 3 #include <stdlib.h> 
 4 #define MaxSize 50
 5 #define InitSize 100
 6 typedef int ElemType;
 7 typedef struct {
 8 ElemType data[MaxSize]; //假定顺序表的元素类型ElemType
 9 int length; //顺序表的当前长度
10 }SqList; //顺序表的类型定义
11 
12 //静态分配。动态分配
13 
14 typedef struct {
15 ElemType *data; //指定动态分配数组的指针
16 int length; //数组的最大容量和当前个数
17 }SeqList; //动态分配数组顺序表的类型定义
18 //c:malloc,c++:new
19 
20 
21 //11 插入操作 i位置(1<=i<L.length+1)
22 bool ListInsert(SqList &L,int i,ElemType e){
23 if(i<1||i>L.length+1) //判断i的插入位置是否合法
24 return false;
25 if(L.length>=MaxSize) //判断存储空间是否已满。满则不插
26 return false;
27 for(int j=L.length;j>=i;j--) //开始是length-1~i,插入数据是i(j)~length-1+1
28 L.data[j]=L.data[j-1]; //i后元素后移 i==>
29 L.data[i-1]=e;//i位置插入
30 L.length++;
31 return true;
32 }
33 
34 //22 删除操作 i位置(1<=i<L.length)(范围和插入不同)
35 bool ListDelete(SqList &L,int i,ElemType &e){
36 if(i<1||i>L.length) 
37 return false;
38 e=L.data[i-1];//i位置删除,下标i-1+1后 即i后元素前移 i<==
39 for(int j=i;j<L.length;j++) //开始是length-1~i,插入数据是i(j)~length-1+1
40 L.data[j-1]=L.data[j]; //i
41 L.length--;
42 return true;
43 }
44 
45 int main()
46 {
47 SqList L;
48 int i=0,e=0;
49 int flag=0;
50 L.length=0;
51 for(i=0;i<10;i++){
52 L.data[i]=i;//赋初值
53 L.length++; //length不能丢
54 }
55 
56 ListInsert(L,2,121);//i代表插入位置是从1开始,不要和数组下标混淆
57 ListInsert(L,3,2333);
58 ListDelete(L,3,e);//一次性操作
59 for(i=0;i<L.length;i++){
60 printf("%d\t",L.data[i]);
61 }
62 return 0;
63

作者:小小黑黑原文地址:https://www.cnblogs.com/upHappy/p/16718577.html

%s 个评论

要回复文章请先登录注册