手撕数据结构一:线性表

阅读: 评论:0

手撕数据结构一:线性表

手撕数据结构一:线性表

线性表可以理解为一维数组,数组即有一段连续的存储空间,可以存储任意类型的数据结构。数组还有两个属性,即数组大小(size)和数组内元素数量(length),实现代码如下:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <algorithm>
 5 #include <vector>
 6 #include <map>
 7 #include <cmath>
 8 
 9 using namespace std;
10 
11 typedef struct Vector {
12     int *data;
13     int size, length;
14 } Vector;
15 
16 Vector *init(int n) {
17     Vector *v = (Vector *)malloc(sizeof(Vector));
18     v->data = (int *)malloc(sizeof(int) * n);
19     v->length = 0;
20     v->size = n;
21     return v;
22 }
23 
24 int insert(Vector *v, int ind, int val) {
25     if (ind < 0 || ind > v->length) return 0;
26     if (v->size == v->length) return 0;
27     for (int i = v->length - 1; i >= ind; i--) {
28         v->data[i + 1] = v->data[i];
29     }
30     v->data[ind] = val;
31     v->length += 1;
32     return 1;
33 }
34 
35 int erase(Vector *v, int ind) {
36     if (ind < 0 || ind > v->length) return 0;
37     for (int i = ind + 1; i < v->length; i++) {
38         v->data[i - 1] = v->data[i];
39     }
40     v->length -= 1;
41     return 1;
42 }
43 
44 void clear(Vector *v) {
45     if (v == NULL) return;
46     free(v->data);
47     free(v);
48     return;
49 }
50 
51 void output(Vector *v) {
52     cout << "arr = [ ";
53     for (int i = 0; i < v->length; i++) {
54         cout << v->data[i] << " ";
55     }
56     cout << "]" << endl;
57     return;
58 }
59 
60 int main() {
61     #define MAX_OP 20
62     int op, ind, val;
63     Vector *v = init(MAX_OP);
64     for (int i = 0; i < MAX_OP; i++) {
65         op = rand() % 4;
66         ind = rand() % (v->length + 3) - 1;
67         val = rand() % 100;
68         switch(op) {
69             case 0:
70             case 1:
71             case 2: {
72                 cout << "insert " << val << " to vector at " << ind << " = " << insert(v, ind, val) << endl;
73                 output(v);
74             } break;
75             case 3: {
76                 cout << "erase element at " << ind << " from vector = " << erase(v, ind) << endl;
77                 output(v);
78             } break;
79         }
80     }
81     clear(v);
82     return 0;
83 }

本博客为原创,如需转载请联系本人!

转载于:.html

本文发布于:2024-01-29 17:32:53,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170652077717101.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:数据结构   线性表
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23