最后合并的C也要有序,并且不能破坏A,B
cpp
#include<iostream>
#include<cstring>
using namespace std;
typedef struct LNode {
int data;
struct LNode* next;
}LinkNode;
void Create(LinkNode*& L, int a[], int l)
{
L = (LinkNode*)malloc(sizeof(LinkNode));
LinkNode* q = L;
for (int i = 0; i < l; i++) {
LinkNode* p = (LinkNode*)malloc(sizeof(LinkNode));
p->data = a[i];
q->next = p;
q = p;
}
q->next = NULL;
}
void Union2(LinkNode* A, LinkNode* B, LinkNode*& C) {
LinkNode* pa, * pb, * pc,*p;
C= (LinkNode*)malloc(sizeof(LinkNode));
pc = C;
pa = A->next;
pb = B->next;//因为建表都是有建头结点的
while (pa != NULL && pb != NULL) {
p = (LinkNode*)malloc(sizeof(LinkNode));
if (pa->data > pb->data) {
p->data = pb->data;
pb = pb->next;
}
else if(pa->data< pb->data){
p->data = pa->data;
pa = pa->next;
}
else {
p->data = pa->data;
pa = pa->next;
pb = pb->next;
}
pc->next = p;
pc = p;
}
while (pa != NULL) {
p= (LinkNode*)malloc(sizeof(LinkNode));
p->data = pa->data;
pc->next = p;
pc = p;
pa = pa->next;
}
while (pb != NULL) {
p = (LinkNode*)malloc(sizeof(LinkNode));
p->data = pb->data;
pc->next = p;
pc = p;
pb = pb->next;
}
pc -> next = NULL;
}
void display(LinkNode* L) {
LinkNode* p = L->next;
while (p != NULL) {
cout << p->data << " ";
p = p->next;
}
}
int main() {
int a1[] = { 1,2,3,4,5 }, b1[] = { 4,5,6 };
LinkNode* A, * B, * C;
Create(A, a1, 4);
display(A);
cout << endl;
Create(B, b1, 3);
display(B);
cout << endl;
Union2(A, B, C);
display(C);
return 0;
}
细节在上一篇博客里;有序合并的思路就就是,同时循环两个表比较,最后在判断哪个表没空就把剩余的加进去