给定两个递增的整数序列A和B,利用链表表示序列A和B,将A和B合并为一个递增的有序序列C,序列C不允许有重复的数据。要求空间复杂度为O(1)。
输入
多组数据,每组数据有三行,第一行为序列A和B的长度n和m,第二行为序列A的n个元素,第三行为序列B的m个元素(元素之间用空格分隔)。n=0且m=0时输入结束。
输出
对于每组数据输出一行,为合并后的序列,每个数据之间用空格分隔。
c版本
#include<stdio.h>
#include<stdlib.h>
//定义链表
typedef struct Node {
int val;
struct Node* next;
}node, * list;
list initlist() {
node* l = (node*)malloc(sizeof(node));
l->next = NULL;
l->val = -1;
return l;
}
void insert(node* a, node* b) {
//insert( a, b2);
//node* s = (node*)malloc(sizeof(node));
node* p = b->next;
a->next = p;
b->next = a;
}
list creat(int len) {
node* head = initlist();
// printf("%d ",head->val );
node* p = head;
// printf("%d ",p->val );
for (int i = 0; i < len; i++) {
node* s = (node*)malloc(sizeof(node));
scanf("%d", &s->val);
s->next = NULL;
p->next = s;
p = s;
}
return head;
}
void combine(node* A, node* B) {
node* b = (node*)malloc(sizeof(node));
node* a = A->next;//a的扫描
node* b1 = B->next;//b的扫描
node* b2 = B;//B的扫描2
while (b1 != NULL && A->next != NULL) {
if (a->val == b1->val) {
A->next = a->next;//删除
a = A->next;
}
else if (a->val < b1->val) {//a小于b,a插入b
A->next = a->next;
insert(a, b2);
b1 = b2->next;
a = A->next;
}
else {//a大于b,b后移
b2 = b1;
b1 = b1->next;
b = b2;
}
}
if (A->next != NULL) {
b->next = A->next;
}
}
void print(node* A) {
node* s = A->next;
for (int i = 0; i < 5; i++) {
printf("%d ", s->val);
s = s->next;
}
}
int main() {
int m = 0;
int count = 0;
int n = 0;
node** a = (node**)malloc(sizeof(node*) * 100);
scanf("%d", &m);
scanf("%d", &n);
for (int i = 0; m != 0 && n != 0; i = i + 2) {
a[i] = creat(m);
a[i + 1] = creat(n);
count = i;
combine(a[i], a[i + 1]);
scanf("%d", &m);
scanf("%d", &n);
}
for (int i = 0; i <= count; i = i + 2) {
node* s = a[i + 1]->next;
while (s != NULL) {
printf("%d", s->val);
s = s->next;
if (s != NULL) {
printf(" ");
}
}
printf("\n");
}
}
c++:
#include <iostream>
using namespace std;
#include<list>
void creatlist(list<int>& L,int len) {
int x = 0;
for (int i = 0; i < len; i++) {
cin >> x;
L.push_back(x);
}
}
void printlist(const list<int>& L) {
for (list<int>::const_iterator it = L.begin(); it != L.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
void combine(list<int>& A, list<int>& B) {
list<int>::iterator a = A.begin();
list<int>::iterator b = B.begin();
while (a != A.end() && b != B.end()) {
if (*a < *b) {
b=B.insert(b, *a);
a++;
}
else if (*a == *b) {
a = A.erase(a);
}
else {
//A.insert(a, B.begin(), b);
b++;
}
}
printlist(B);
}
int main() {
int m=0, n = 0;
cin >> m;
cin >> n;
while (m != 0 && n != 0) {
list<int>A;
list<int>B;
creatlist(A,m);
creatlist(B,n);
//cout << "A" << endl;
//printlist(A);
//cout << "B" << endl;
//printlist(B);
combine(A, B);
//cout << "A" << endl;
//printlist(A);
//cout << "B" << endl;
//printlist(B);
cin >> m;
cin >> n;
}
}