基于链表的两个集合的差集
#include <iostream>
using namespace std;
typedef struct ListNode{
int val;
ListNode* next;
ListNode():val(0),next(nullptr){}
ListNode(int x):val(x),next(nullptr){}
}*LinkList,ListNode;
//建立单链表(尾插法),带头结点
LinkList TailInsert(int n){
ListNode* head = new ListNode;
ListNode* r = head;
int x;
for (int i = 0; i < n; ++i){
cin>>x;
ListNode* p = new ListNode(x);
r->next = p;
r = p;
}
return head;
}
//头插法
LinkList HeadInsert(int n){
ListNode* head = new ListNode;
int x;
for (int i = 0; i < n; ++i){
cin>>x;
ListNode* p = new ListNode(x);
p->next = head->next;
head->next = p;
}
return head;
}
//输出链表操作,并输出个数
void count_print(LinkList L){
ListNode * p = L->next;
int n = 0;
while(p){
cout<<p->val;
if(p->next != nullptr){
cout<<" ";
}
n++;
p = p->next;
}
cout<<endl;
cout<<n<<endl;
}
//1 3 5 7 9
//1 2 3 4 5
//求差集
LinkList subtract(LinkList A,LinkList B){
ListNode* p = A->next;
ListNode* q = B->next;
ListNode * r = A;
while(p && q){
if(p->val < q->val){
r->next = p;
r = p;
p = p->next;
}else if(p->val > q->val){
q = q->next;
} else{
p = p->next;
q = q->next;
}
}
//将p剩下的加入的序列中
while(p){
r->next = p;
r = p;
p = p->next;
}
r->next = nullptr;
return A;
}
int main(){
int n,m;
cin>>n>>m;
while(!(n==0 && m==0)){
LinkList A = TailInsert(n);
LinkList B = TailInsert(m);
LinkList C = subtract(A,B);
count_print(C);
cin>>n>>m;
}
return 0;
}