#include<bits/stdc++.h>
using namespace std;
typedef struct Node{
int data;
struct Node *next;
}Node,*Linklist;
Linklist Substract(Linklist &LB, Linklist &LC){//求lb-lc
Node *q,*p = LB->next,*pre = LB;
while(p){
q = LC->next;
while(q){
if(q->data == p->data) break;
q = q->next;
}
if(q == NULL){
pre = p;
p = p->next;
}
else {//la中有和q->data相同的元素
pre->next = p->next;
delete p;
p = pre->next;
}
}
return LB;
}
Linklist insertlist(Linklist &L){//尾插
int c;
Node *s;
L = (Linklist)malloc(sizeof(Node));
L->next = NULL;
scanf("%d",&c);
while(c != 999){
s = (Node *)malloc(sizeof(Node));
s->data = c;
s->next = L->next;
L->next = s;
scanf("%d",&c);
}
return L;
}
// Linklist insertlist(Linklist &L){//头插
// int c;
// L = (Linklist)malloc(sizeof(Node));
// Node *s,*r = L;
// scanf("%cd",&c);
// while(c != 999){
// s = (Node *)malloc(sizeof(Node));
// s->data = c;
// r->next = s;
// r = s;
// scanf("%d",&c);
// }
// r->next = NULL;
// return L;
// }
Linklist Union(Linklist &la, Linklist &lb){//求la和lb的并集
Node *p = la->next,*q,*s,*tail;
s = la;
while(p){
printf("%d\n",num++);
q = lb->next;
while(q){
if(q->data == p->data) break;
q = q->next;
}
if(q){//lb中有和p->data相同的元素
s->next = p->next;
delete p;
p = s->next;
}
else {
s = p;
p = p->next;
}
}
q = lb->next;
while(q->next != NULL) q = q->next;
tail = q;
tail->next = la->next;
la->next = lb->next;
delete lb;
return la;
}
int main(){
Linklist la,lb,lc;
insertlist(la);//建立la链表
insertlist(lb);//建立lb链表
insertlist(lc);//建立lc链表
Substract(lb,lc);//将lb-lc返回lb
Node *next1 = lb->next;
printf("lb-lc为:");
while(next1 != NULL){
printf("%d ",next1->data);
next1 = next1->next;
}
cout << endl;
Union(la,lb);//求la和lb的并集返回la
printf("la并lb为:");
Node *next2 = la->next;
while(next2 != NULL){
printf("%d ",next2->data);
next2 = next2->next;
}
return 0;
}
三个带头结点的链表求a交(b-c)
最新推荐文章于 2022-01-09 16:54:21 发布