A和B两个单链表递增有序排列,求出A和B的交集C,仍然以递增的单链表排序。
输入输出样例:1组
#1
样例输入:
5//A链表中包含的元素个数
1 2 3 4 5//A链表中的元素
4//B链表中包含的元素个数
3 4 5 6//B链表中的元素
样例输出:
3 4 5
//注意
//1:该程序每次运行的时间必须小于10秒,否则会超时,程序超时将不会测试剩余的测试集
//2:该程序每次运行使用的内存不能超过1M,否则会返回错误
//3:该程序每次运行输出的结果最多显示1000个字符(多余的不显示),每行末尾的所有空格用□表示
#include <iostream>
#include<stdlib.h>
using namespace std;
typedef struct Incode
{
int data;
struct Incode *next;
}LNode,*LinkList;
LinkList Delete(LinkList head);
LinkList Create_List(int n);
void PrintList(LinkList head);
LinkList Intersection(LinkList A,LinkList B);
int main()
{
LinkList A,B,C;
int m,n;//m,n分别为A,B链表的节点个数
//建立A链表并删除表中重复元素
cin>>m;
A=Create_List(m);
A=Delete(A);
//建立B链表并删除表中重复元素
cin>>n;
B=Create_List(n);
B=Delete(B);
C=Intersection(A,B);
PrintList(C);
return 0;
}
LinkList Create_List(int n)
{
LinkList head;
head = (LinkList)malloc(sizeof(LNode));
head->next = NULL;
head->data = -1;
LNode *p, *q;
p = head;
for(int i = 0; i < n; i++)
{
int x;
cin>>x;
q = (LNode *)malloc(sizeof(LNode));
q->data = x;
q->next = NULL;
p->next = q;
p = q;
}
return head;
}
LinkList Intersection(LinkList A,LinkList B)
{
LinkList head;
head = (LinkList)malloc(sizeof(LNode));
head->next = NULL;
head->data = -1;
LNode *p,*q,*rear;
rear=head;
p=A->next;
q=B->next;
while(p!=NULL&&q!=NULL)
{
if(p->data==q->data)
{
LNode *r;
r= (LNode *)malloc(sizeof(LNode));
r->data=p->data;
r->next=NULL;
rear->next=r;
rear=r;
p=p->next;
q=q->next;
}
else if(p->data<q->data)
{
p=p->next;
}
else
{
q=q->next;
}
}
return head;
}
LinkList Delete(LinkList head)
{
LinkList p,q;
p = head->next;
if(p==NULL) return head;
while(p!=NULL)
{
q = p;
while(q->next!=NULL)
{
if(p->data==q->next->data)
{
q->next = q->next->next;
}
else
{
q = q->next;
}
}
p = p->next;
}
return head;
}
void PrintList(LinkList head)
{
LinkList p=head->next;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
}