/*
单链表AB递增有序
找到相同的元素放到A中(最后A是交集)
最后的交集元素各不相同
*/
#include <iostream>
#include <cstdlib>
using namespace std;
const int flag = -1;
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode *next;
}*LinkList;
void tailInsert(LinkList &L){
int x;
L = (LinkList)malloc(sizeof(LNode));
LinkList r;
r = L;
while(cin>>x && x!=flag){
LinkList s = (LinkList)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r = s;
}
r->next = NULL;
}
void unionList(LinkList &A, LinkList B){
LinkList pa, pb;
pa = A;
pb = B->next;
while(pa->next && pb){
if(pa->next->data > pb->data)
pb = pb->next;
else if(pa->next->data < pb->data){
LinkList t = pa->next;
pa->next = t->next;
free(t);
}else{ //找到共同的结点
pa = pa->next;
pb = pb->next;
}
}
}
void printList(LinkList L){
LinkList p = L->next;
while(p){
cout << p->data << " " ;
p = p->next;
}
cout << endl;
}
int main(){
LinkList A, B;
cout << "输入A表元素:";
tailInsert(A);
cout << "输入B表元素:";
tailInsert(B);
cout << "A操作前:" ;
printList(A) ;
cout << "B操作前:" ;
printList(B) ;
unionList(A, B);
cout << "A操作后:" ;
printList(A) ;
return 0;
}
单链表(升序)交集,结果放到一个单链表中
最新推荐文章于 2022-07-04 12:02:28 发布