使用共享的或者自编的顺序表/单链表代码,完成2个有序序列的合并功能实现,用以下数据进行测试: u LA=(3,5,8,9) LB=(2,6,8,10,11,15,20) u 则LC=(2,3,5,6,8,8,9,10,11,15,20) 确保能够创建顺序表和单链表存放LA,LB内容;
时间: 2023-05-14 15:04:41 浏览: 93
以下是使用顺序表实现的代码:
#include <iostream>
using namespace std;
const int MAXSIZE = 100;
typedef struct {
int data[MAXSIZE];
int length;
} SqList;
void InitList(SqList &L) {
L.length = 0;
}
void MergeList(SqList La, SqList Lb, SqList &Lc) {
int i = 0, j = 0, k = 0;
while (i < La.length && j < Lb.length) {
if (La.data[i] <= Lb.data[j]) {
Lc.data[k++] = La.data[i++];
} else {
Lc.data[k++] = Lb.data[j++];
}
}
while (i < La.length) {
Lc.data[k++] = La.data[i++];
}
while (j < Lb.length) {
Lc.data[k++] = Lb.data[j++];
}
Lc.length = k;
}
int main() {
SqList La, Lb, Lc;
InitList(La);
InitList(Lb);
InitList(Lc);
La.data[0] = 3;
La.data[1] = 5;
La.data[2] = 8;
La.data[3] = 9;
La.length = 4;
Lb.data[0] = 2;
Lb.data[1] = 6;
Lb.data[2] = 8;
Lb.data[3] = 10;
Lb.data[4] = 11;
Lb.data[5] = 15;
Lb.data[6] = 20;
Lb.length = 7;
MergeList(La, Lb, Lc);
for (int i = 0; i < Lc.length; i++) {
cout << Lc.data[i] << " ";
}
cout << endl;
return 0;
}
以下是使用单链表实现的代码:
#include <iostream>
using namespace std;
typedef struct LNode {
int data;
struct LNode *next;
} LNode, *LinkList;
void InitList(LinkList &L) {
L = new LNode;
L->next = NULL;
}
void MergeList(LinkList La, LinkList Lb, LinkList &Lc) {
LNode *pa = La->next, *pb = Lb->next, *pc = Lc = new LNode;
while (pa && pb) {
if (pa->data <= pb->data) {
pc->next = pa;
pc = pa;
pa = pa->next;
} else {
pc->next = pb;
pc = pb;
pb = pb->next;
}
}
pc->next = pa ? pa : pb;
}
int main() {
LinkList La, Lb, Lc;
InitList(La);
InitList(Lb);
InitList(Lc);
LNode *p = La;
p->next = new LNode;
p->next->data = 3;
p->next->next = new LNode;
p->next->next->data = 5;
p->next->next->next = new LNode;
p->next->next->next->data = 8;
p->next->next->next->next = new LNode;
p->next->next->next->next->data = 9;
p->next->next->next->next->next = NULL;
p = Lb;
p->next = new LNode;
p->next->data = 2;
p->next->next = new LNode;
p->next->next->data = 6;
p->next->next->next = new LNode;
p->next->next->next->data = 8;
p->next->next->next->next = new LNode;
p->next->next->next->next->data = 10;
p->next->next->next->next->next = new LNode;
p->next->next->next->next->next->data = 11;
p->next->next->next->next->next->next = new LNode;
p->next->next->next->next->next->next->data = 15;
p->next->next->next->next->next->next->next = new LNode;
p->next->next->next->next->next->next->next->data = 20;
p->next->next->next->next->next->next->next->next = NULL;
MergeList(La, Lb, Lc);
p = Lc->next;
while (p) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
return 0;
}
阅读全文