-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1.1.cpp
More file actions
139 lines (126 loc) · 2.46 KB
/
1.1.cpp
File metadata and controls
139 lines (126 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 100
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize]; // 存储空间
int length; // 长度
} SqList;
// 初始化线性表
void InitList(SqList *&L)
{
L = (SqList *)malloc(sizeof(SqList));
L->length = 0;
}
// 销毁线性表
void DestroyList(SqList *&L)
{
free(L);
L = NULL;
}
// 判断是否为空
int ListEmpty(SqList *L)
{
return (L->length == 0);
}
// 求长度
int ListLength(SqList *L)
{
return L->length;
}
// 输出线性表
void DispList(SqList *L)
{
int i;
for (i = 0; i < L->length; i++)
printf("%d ", L->data[i]);
printf("\n");
}
// 取元素
int GetElem(SqList *L, int i, ElemType &e)
{
if (i < 1 || i > L->length)
return 0; // 越界
e = L->data[i - 1];
return 1;
}
// 按值查找
int LocateElem(SqList *L, ElemType e)
{
int i = 0;
while (i < L->length && L->data[i] != e)
i++;
if (i >= L->length)
return 0; // 不存在
else
return i + 1; // 返回逻辑位置
}
// 插入
int ListInsert(SqList *&L, int i, ElemType e)
{
int j;
if (i < 1 || i > L->length + 1 || L->length == MaxSize)
return 0; // 越界
for (j = L->length; j >= i; j--)
{
L->data[j] = L->data[j - 1];
}
L->data[i - 1] = e;
L->length++;
return 1;
}
// 删除
int ListDelete(SqList *&L, int i, ElemType &e)
{
int j;
if (i < 1 || i > L->length)
return 0;
e = L->data[i - 1];
for (j = i; j < L->length; j++)
L->data[j - 1] = L->data[j];
L->length--;
return 1;
}
// 求并集
void UnionList(SqList *&La, SqList *Lb)
{
int i, la_len, lb_len;
ElemType e;
la_len = ListLength(La);
lb_len = ListLength(Lb);
for (i = 1; i <= lb_len; i++)
{
GetElem(Lb, i, e);
if (!LocateElem(La, e))
ListInsert(La, ++la_len, e);
}
}
// 创建线性表
void CreateList(SqList *&L, ElemType a[], int n)
{
int i;
L = (SqList *)malloc(sizeof(SqList));
for (i = 0; i < n; i++)
L->data[i] = a[i];
L->length = n;
}
int main()
{
SqList *La, *Lb;
int a1[] = {1, 2, 3, 4, 5};
int a2[] = {2, 4, 8, 10};
int n1 = 5, n2 = 4;
CreateList(La, a1, n1);
CreateList(Lb, a2, n2);
printf("原La: ");
DispList(La);
printf("原Lb: ");
DispList(Lb);
UnionList(La, Lb);
printf("并集La: ");
DispList(La);
DestroyList(La);
DestroyList(Lb);
return 0;
}