您的位置:首页 > 其它

任意长度的两个整数集合求并集与交集

2012-12-13 17:05 337 查看
//将以上数组为数据结构的程序实现改为单链表结构,可以对任意长度的两个整数集合求并集与交集

#include <iostream>

using namespace std;

struct LinkNode{

 int data;

 LinkNode *next;

};

int check(int elem,LinkNode *head);

int main(){

 int len1,len2;

 cout<<"请分别输入两动态数组的长度:"<<endl;

 cin>>len1>>len2;

 int *p1=new int[len1];

 int *p2=new int[len2];

 cout<<"输入动态数组a1的数组元素:"<<endl;

 for (int i=0;i<len1;i++)

  cin>>p1[i];

 cout<<"输入动态数组a2的数组元素:"<<endl;

 for (int j=0;j<len2;j++)

  cin>>p2[j];

 cout<<"您输入的动态数组a1为:"<<endl;

 for(i=0;i<len1;i++)

  cout<<p1[i]<<" ";

 cout<<endl;

 cout<<"您输入的动态数组a2为:"<<endl;

 for(j=0;j<len2;j++)

  cout<<p2[j]<<" ";

 cout<<endl;

 LinkNode *head1,*head2,*tail1,*tail2,*temp,*head,*tail;

 head1=new LinkNode;//将动态数组p1赋值给链表head1;

 int k=0;

 if(head1==NULL) return NULL;

 else

 {

  head1->data=p1[k];

  head1->next=NULL;

  tail1=head1;

  k++;

 }

 while (k<len1)

 {

  temp=new LinkNode;

  temp->data=p1[k];

  temp->next=NULL;

  tail1->next=temp;

  tail1=temp;

  k++;

 }

 head2=new LinkNode;//将动态数组p2赋值给链表head2;

 int m=0;

 if(head2==NULL) return NULL;

 else

 {

  head2->data=p2[m];

  head2->next=NULL;

  tail2=head2;

  m++;

 }

 while (m<len2)

 {

  temp=new LinkNode;

  temp->data=p2[m];

  temp->next=NULL;

  tail2->next=temp;

  tail2=temp;

  m++;

 }

 cout<<"这两个动态数组的交集为:"<<endl;//交集的求法应还可以优化

 for (head2;head2!=NULL;head2=head2->next){

   if (check(head2->data,head1)==1)

   {

    temp=new LinkNode;

    temp->data=head2->data;

    temp->next=NULL;

    tail1->next=temp;

    tail1=temp;

   }

   else

   {

    cout<<head2->data<<" ";

   }

  }

 cout<<endl;

 cout<<"这两个动态数组的并集为:"<<endl;

 while(head1){

  cout<<head1->data<<" ";

  head1=head1->next;

 }

 cout<<endl; 

 return 0;

}

int check(int elem,LinkNode *head){//判断插入的链表值是否和前面的重复

 for (head;head!=NULL;head=head->next)

  if(elem==head->data)

   return 0;

  return 1;

 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: