2024-3-15

Small changes
This commit is contained in:
2024-03-15 08:34:30 +08:00
parent 0dd8916b05
commit 8933bff3c7
2 changed files with 6 additions and 23 deletions

View File

@@ -32,10 +32,7 @@ void Union(LNode<DT>*& A, LNode<DT>*& B, int length_a, int length_b)
{ {
int temp; int temp;
GetElem_i(B, i, temp); // You should manually get the element instead of using B.elem[i] GetElem_i(B, i, temp); // You should manually get the element instead of using B.elem[i]
if (LocateElem_e(A, temp) == 0) if (LocateElem_e(A, temp) == 0) InsertElem_i(A, ++length_a, temp); // ++length_a to always insert at the end
{
InsertElem_i(A, ++length_a, temp); // ++length_a to always insert at the end
}
} }
} }
template <class DT> template <class DT>
@@ -48,7 +45,8 @@ void Intersection(LNode<DT>*& A, LNode<DT>*& B, int length_a)
GetElem_i(A, i, temp); GetElem_i(A, i, temp);
if (LocateElem_e(B, temp) == 0) if (LocateElem_e(B, temp) == 0)
{ {
DeleElem_i(A, i); DeleElem_i(A, i--);
length_a--;
} }
} }
} }
@@ -72,10 +70,7 @@ int main()
Union(A, B, length_a, length_b); // You should manually pass the length of the list instead of using A.length Union(A, B, length_a, length_b); // You should manually pass the length of the list instead of using A.length
cout << "AB: "; cout << "AB: ";
DispList(A); DispList(A);
while (true) while (true) if (!DeleElem_i(A, length_a + 1)) break; // Delete elements after the original list A
{
if (!DeleElem_i(A, length_a + 1)) break; // Delete elements after the original list A
}
Intersection(A, B, length_a); Intersection(A, B, length_a);
cout << "A∩B: "; cout << "A∩B: ";
DispList(A); DispList(A);

View File

@@ -25,25 +25,13 @@ bool CreateListNoRepeat(SqList<DT>& L, int n)
template <class DT> template <class DT>
void Union(SqList<DT>& A, const SqList<DT>& B) void Union(SqList<DT>& A, const SqList<DT>& B)
{ {
for (int i = 0; i < B.length; ++i) for (int i = 0; i < B.length; ++i) if (LocateElem_e(A, B.elem[i]) == 0) InsertElem_i(A, A.length + 1, B.elem[i]);
{
if (LocateElem_e(A, B.elem[i]) == 0)
{
InsertElem_i(A, A.length + 1, B.elem[i]);
}
}
} }
template <class DT> template <class DT>
void Intersection(SqList<DT>& A, const SqList<DT>& B) void Intersection(SqList<DT>& A, const SqList<DT>& B)
{ {
int k = 0; int k = 0;
for (int i = 0; i < A.length; ++i) for (int i = 0; i < A.length; ++i) if (LocateElem_e(B, A.elem[i]) > 0) A.elem[k++] = A.elem[i];
{
if (LocateElem_e(B, A.elem[i]) > 0)
{
A.elem[k++] = A.elem[i];
}
}
A.length = k; A.length = k;
} }
int main() int main()