学习版
【c语言】
1.顺序表元素类型
2.顺序表的初始化
3.顺序表的插入
4.顺序表的合并
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
typedef struct {
int* data; // 数据数组的指针
int length; // 当前顺序表中的元素个数
int capacity; // 顺序表的总容量
} SeqList;
// 初始化顺序表
void init(SeqList* list, int size) {
list->data = (int*)malloc(size * sizeof(int));
list->length = 0;
list->capacity = size;
}
// 插入元素到顺序表中
void insert(SeqList* list, int value) {
if (list->length >= list->capacity) {
std::cout << "顺序表已满,无法插入元素" << std::endl;
return;
}
list->data[list->length++] = value;
}
// 打印顺序表
void print(SeqList* list) {
for (int i = 0; i < list->length; i++) {
std::cout << list->data[i] << " ";
}
}
// 释放顺序表的内存
void destroy(SeqList* list) {
free(list->data);
list->length = 0;
list->capacity = 0;
list->data = NULL;
}
// 合并两个顺序表
SeqList mergeSeqList(SeqList* list1, SeqList* list2) {
SeqList mergeList;
mergeList.capacity = list1->capacity + list2->capacity;
mergeList.data = (int*)malloc(mergeList.capacity * sizeof(int));
int i;
for (i = 0; i < list1->length; i++) {
mergeList.data[i] = list1->data[i];
}
int j;
for (j = 0; j < list2->length; j++) {
mergeList.data[i + j] = list2->data[j];
}
mergeList.length = i + j;
return mergeList;
}
int main() {
SeqList list1, list2;
int n;
std::cin >> n;
init(&list1, n);
int a;
while (n--) {
std::cin >> a;
insert(&list1, a);
}
int m;
std::cin >> m;
init(&list2, m);
while (m--) {
std::cin >> a;
insert(&list2, a);
}
SeqList list3 = mergeSeqList(&list1, &list2);
destroy(&list1);
destroy(&list2);
std::sort(list3.data, list3.data + list3.length, [](int a, int b) {
return a < b;
});
print(&list3);
destroy(&list3);
}
【C++】
【速通版】
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
int n, m, a;
std::cin >> n;
std::vector<int> vec;
while (n--) {
std::cin >> a;
vec.push_back(a);
}
std::cin >> m;
while (m--) {
std::cin >> a;
vec.push_back(a);
}
std::sort(vec.begin(), vec.end());
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}