将两个有序顺序表/链表合并 成一个(差集)
A: 1,2,3,4,5
B:2,4,6,9
C=A-B:1,3,5;
类似归并排序,改一改就行
#include <cstdio>
#include <cstdlib>
/**********************PART1***************************/
struct Sqlist {
int *num;
int len;
}A,B;
Sqlist Dif(Sqlist A,Sqlist B) { //A-B
int i = 0,j = 0;
Sqlist C;
C.len = 0;
C.num = (int *)malloc(sizeof(int)*A.len);
while (i < A.len && j < B.len) {
while (j < B.len && B.num[j] < A.num[i]) j++;
while (i < A.len && j < B.len && A.num[i] < B.num[j]) C.num[C.len++] = A.num[i++];
while (i < A.len && j < B.len && A.num[i] == B.num[j]) i++;
}
while (i < A.len) C.num[C.len++] = A.num[i++];
return C;
}
void WorkSqlist() {
int i;
puts("Input A:");
scanf("%d",&A.len);
A.num = (int *)malloc(sizeof(int)*A.len);
for (i = 0; i < A.len; i++) scanf("%d",&A.num[i]);
puts("Input B:");
scanf("%d",&B.len);
B.num = (int *)malloc(sizeof(int)*B.len);
for (i = 0; i < B.len; i++) scanf("%d",&B.num[i]);
Sqlist C = Dif(A,B);
printf("Len:%d\n",C.len);
for (i = 0; i < C.len; i++) printf("%d ",C.num[i]);
puts("\nDone!");
}
/**********************PART2***************************/
typedef struct Node {
int num;
Node *next;
Node():num(0),next(NULL){}
} *Linklist;
void Init(Linklist L) {
while (true) {
L->next = new Node;
L = L->next;
scanf("%d",&L->num);
puts("Whether to continue?(y/n)");
char opt;
while((opt = getchar()) != 'n' && opt != 'y');
if (opt == 'n') break;
}
}
Linklist Dif(Linklist A,Linklist B) {
Linklist L = new Node,C = L;
A = A->next;
B = B->next;
while (A && B) {
while (B && B->num < A->num) B = B->next;
while (A && B && A->num < B->num) {
C->next = new Node;
C = C->next;
C->num = A->num;
A = A->next;
}
while (A && B && A->num == B->num) A = A->next;
}
while (A) {
C->next = new Node;
C = C->next;
C->num = A->num;
A = A->next;
}
return L;
}
void WorkLinklist() {
Linklist A = new Node,B = new Node;
puts("Input A:");
Init(A);
puts("Input B:");
Init(B);
Linklist C = Dif(A,B);
while(C->next)
printf("%d ",(C = C->next)->num);
puts("Done");
}
/**********************MAIN***************************/
int main() {
WorkSqlist();
WorkLinklist();
return 0;
}