熟话说, 万事开头难, 顺序表还是花了一些时间的, 那么这么晚了, 解释就改天再写吧
看代码
1 #include <bits/stdc++.h> 2 #define ListSize 100 3 using namespace std; 4 5 typedef int DateType; 6 typedef struct { 7 DateType date[ListSize]; 8 int length; 9 } List, *PList; 10 11 void creat_list(PList& p); 12 void insert_list(PList p, DateType a, int sub); 13 void delete_list(PList p, int sub); 14 bool search_list(PList p, DateType target); 15 void travel_list(PList p); 16 17 int main(void) { 18 PList p = NULL; 19 creat_list(p); 20 //放10个数据进去 21 for (int i = 0; i < 10; i++) { 22 insert_list(p, pow(i, 2), i + 1); 23 } 24 //测试一下放进去没 25 travel_list(p); 26 27 //测试delete 28 delete_list(p, 7); 29 travel_list(p); 30 31 //测试search 32 if (search_list(p, 81)) { 33 cout << "Get it!" << endl; 34 } 35 else { 36 cout << "No this number!" << endl; 37 } 38 39 return 0; 40 } 41 42 //建表 43 void creat_list(PList& p) { 44 if ((p = (PList)malloc(sizeof(List))) == NULL) { 45 cout << "Creat error!" << endl; 46 exit(1); 47 } 48 //cout << 1; 49 p->length = 0; 50 } 51 52 //增(插入) 53 void insert_list(PList p, DateType a, int sub) { 54 p->length++; 55 if (p == NULL || sub <= 0 || sub > p->length + 1 || sub > ListSize) { 56 cout << "Insert error!" << endl; 57 } 58 else { 59 for (int i = p->length - 1; i >= sub; i--) { 60 p->date[i + 1] = p->date[i]; 61 } 62 p->date[sub] = a; 63 } 64 } 65 66 //删 67 void delete_list(PList p, int sub) { 68 if (p == NULL || sub <= 0 || sub > p->length || sub > ListSize) { 69 cout << "Delete error!" << endl; 70 } 71 else { 72 for (int i = sub; i < p->length; i++) { 73 p->date[i] = p->date[i + 1]; 74 } 75 p->length--; 76 } 77 } 78 79 //查 80 bool search_list(PList p, DateType target) { 81 if (p == NULL) { 82 cout << "A empty list!" << endl; 83 return false; 84 } 85 for (int i = 1; i <= p->length; i++) { 86 if (p->date[i] == target) { 87 return true; 88 } 89 } 90 return false; 91 } 92 93 //遍历 94 void travel_list(PList p) { 95 for (int i= 1; i <= p->length; i++) { 96 printf("p->Date[%d] = %d\n", i, p->date[i]); 97 } 98 }
有问题,请联系760521757@qq.com