#include<stdio.h>
#include<stdlib.h>
#define Max 15
typedef struct {
int length;
int* data;
}SeqList;
void InitList(SeqList& L) {
L.data = new int[Max];
if (!L.data)
return;
L.length = 0;
}
void PrintList(SeqList L) {
for (int i = 0; i < L.length; i++)
printf("%d ", L.data[i]);
printf("\n");
}
void CreateList(SeqList& L) {
int n;
printf("请输入顺序表元素个数:\n");
scanf_s("%d", &n);
printf("输入元素:\n");
for (int i = 0; i < n; i++) {
scanf_s("%d", &L.data[i]);
}
L.length = n;
}
void MergeList(SeqList A, SeqList B, SeqList& C) {
int* pa, * pb, * pa_last, * pb_last, * pc;
pa = A.data;
pb = B.data;
pa_last = A.data + A.length - 1;
pb_last = B.data + B.length - 1;
C.length = A.length + B.length;
C.data = new int[C.length];
pc = C.data;
while (pa <= pa_last && pb <= pb_last) {
if (*pa <= *pb) {
*pc = *pa;
pc++;
pa++;
}
else
{
*pc = *pb;
pc++;
pb++;
}
}
while (pa <= pa_last) {
*pc = *pa;
pc++;
pa++;
}
while (pb <= pb_last) {
*pc = *pb;
pc++;
pb++;
}
}
int main() {
SeqList A, B, C;
InitList(A);
InitList(B);
CreateList(A);
CreateList(B);
printf("顺序表A元素: ");
PrintList(A);
printf("顺序表B元素: ");
PrintList(B);
MergeList(A, B, C);
PrintList(C);
}
顺序表的合并
于 2024-01-17 10:25:27 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)