单链表
集合合并(去重)
#include<iostream>
#include<algorithm>
using namespace std;
//创建链表的存储结构
typedef struct LNode{
int data;
struct LNode *next;//指针域
}LNode ,*LinkList;//LinkList为指向结构体LNode的指针类型
LinkList creation(LinkList &L, int n){//建立链表
int i;
LinkList p;
L = (LinkList)malloc(sizeof(LNode));
L->next=NULL;
LinkList q;
q = L;
for(int i = 0;i < n;i++){
p = (LinkList)malloc(sizeof(LNode));//申请空间
cin>>p->data;
p->next = NULL;
q->next = p;//p结点插到q后
q = p;//q指向新的尾结点p
}
return L;
}
void pri(LinkList &L){//输出链表
LinkList p;
p = L->next;
while(p){
cout<<p->data<<" ";
p = p->next;
}
}
void merge(LinkList &La, LinkList &Lb, LinkList &Lc){//合并链表
LinkList pa, pb ,pc;
pa = La->next;
pb = Lb->next;//pa pb分别指向La,Lb的首元结点
Lc = La;
pc = Lc;
while(pa&&pb){//hai wei daoda La and Lb de weijiedian
if(pa->data < pb->data){
pc->next=pa;
pc = pa;
pa = pa->next;
}
else if(pa->data==pb->data){
pc->next = pa;
pc = pa;
pa = pa->next;
pb = pb->next;
vim = 1;
}
else{
pc->next = pb;
pc = pb;
pb = pb->next;
}
}
pc->next=pa?pa:pb;
delete Lb;//释放Lb的头结点
}
int main(){
int n, m;
LinkList La, Lb, Lc;
cin>>n;
creation(La,n);
//pri(La);
cin>>m;
creation(Lb,m);
//pri(Lb);
merge(La,Lb,Lc);
pri(Lc);
return 0;
}