有序表的并(不去除重复元素):
①通过数组实现:
输入大小分别为 m, n 的有序数组 a[i], b[i],输出两者的并集(有序)。
#include <stdio.h>
const int maxn = 1000000;
int m, n;
int a[maxn + 1];
int b[maxn + 1];
int c[maxn * 2 + 1];
int main() {
scanf("%d%d", &m, &n);
for (int i = 0; i < m; i++) scanf("%d", &a[i]);
for (int i = 0; i < n; i++) scanf("%d", &b[i]);
int p = 0, q = 0, s = 0;
while (p < m && q < n)
if (a[p] < b[q]) c[s++] = a[p++];
else c[s++] = b[q++];
while (p < m) c[s++] = a[p++];
while (q < n) c[s++] = b[q++];
for (int i = 0; i < s; i++)
printf("%d ", c[i]);
return 0;
}
②通过链表实现:
#include<stdio.h>
#include<malloc.h>
struct node{
int data;
node *next;
};
node *createLinkList(int n) { // 尾插入法
node *head, *tail, *p;
head = tail = (node*) malloc(sizeof(node));
tail->next = NULL;
for (int i = 0; i < n; ++ i) {
int x;
scanf("%d", &x);
p = (node*) malloc(sizeof(node));
p->data = x; p->next = NULL;
tail->next = p; tail = p;
}
return head;
}
void LinkList_Print(node *A) {
node *p = A->next;
while (p != NULL) {
printf("%d ", p->data); p = p->next;
}
}
node *combineLinkList(node *A, node *B) {
node *head, *tail, *p;
head = tail = (node*)malloc(sizeof(node));
tail->next = NULL;
A = A->next; B = B->next;
while (A != NULL && B != NULL) {
if (A->data <= B->data) {
p = (node*)malloc(sizeof(node));
p->data = A->data; p->next = NULL;
tail->next = p; tail = p;
A = A->next;
} else {
p = (node*)malloc(sizeof(node));
p->data = B->data; p->next = NULL;
tail->next = p; tail = p;
B = B->next;
}
}
// 处理剩余的元素
while (A != NULL) {
p = (node*)malloc(sizeof(node));
p->data = A->data; p->next = NULL;
tail->next = p; tail = p;
A = A->next;
}
while (B != NULL) {
p = (node*)malloc(sizeof(node));
p->data = B->data; p->next = NULL;
tail->next = p; tail = p;
B = B->next;
}
return head;
}
int main() {
int m, n;
scanf("%d%d", &m, &n);
node *A = createLinkList(m);
node *B = createLinkList(n);
node *C = combineLinkList(A, B);
LinkList_Print(C);
return 0;
}
有序表的交(链表实现):
#include<stdio.h>
#include<malloc.h>
struct node{
int data;
node *next;
};
node *createLinkList(int n) { // 尾插入法
node *head, *tail, *p;
head = tail = (node*) malloc(sizeof(node));
tail->next = NULL;
for (int i = 0; i < n; ++ i) {
int x;
scanf("%d", &x);
p = (node*) malloc(sizeof(node));
p->data = x; p->next = NULL;
tail->next = p; tail = p;
}
return head;
}
void LinkList_Print(node *A) {
node *p = A->next;
while (p != NULL) {
printf("%d ", p->data); p = p->next;
}
}
node *combineLinkList(node *A, node *B) {
node *head, *tail, *p;
head = tail = (node*)malloc(sizeof(node));
tail->next = NULL;
A = A->next; B = B->next;
while (A != NULL && B != NULL) {
if (A->data < B->data) A = A->next;
else if (B->data < A->data) B = B->next;
else{
p = (node*) malloc(sizeof(node));
p->data = A->data; p->next = NULL;
tail->next = p; tail = p;
A = A->next; B = B->next;
}
}
return head;
}
int main() {
int m, n;
scanf("%d%d", &m, &n);
node *A = createLinkList(m);
node *B = createLinkList(n);
node *C = combineLinkList(A, B);
LinkList_Print(C);
return 0;
}