2017年吉林大学考研初试专业课966 第七题

代码

  1 #include <iostream>
  2 #include <cstdio>
  3 #include <cstdlib>
  4 using namespace std;
  5 typedef struct _node{
  6     int value;
  7     struct _node *next;
  8 } Node;
  9 typedef  struct  _list{
 10     Node* head;
 11 }List;
 12 void addl(List *pList,int number){
 13     Node *p=(Node*)malloc(sizeof(Node));
 14     p->value=number;
 15     p->next=NULL;
 16     Node *last=pList->head;
 17     if(last){
 18         while(last->next){
 19             last=last->next;
 20         }
 21         last->next=p;
 22     }else{
 23         pList->head=p;
 24     }
 25 }
 26 void print(List *pList){
 27     Node *p;
 28     for(p=pList->head;p;p=p->next){
 29         printf("%d ",p->value);
 30     }
 31     printf("\n");
 32 }
 33 
 34 List UnionSet(List *list1,List *list2){
 35     Node *p,*p3;
 36     List list3;
 37     list3.head=NULL;
 38     for(p=list1->head;p;p=p->next){
 39         int flag;
 40         flag=0;
 41         //遍历新的链表list3,是否纯正这个元素,如果不纯在,把这个元素添加在list3中
 42         for(p3=list3.head;p3;p3=p3->next){
 43             if(p3->value==p->value){
 44                 flag=1;
 45                 break;
 46             }
 47         }
 48         if(flag==0){
 49             addl(&list3, p->value);
 50         }
 51     }
 52     for(p=list2->head;p;p=p->next){
 53         int flag;
 54         flag=0;
 55         //遍历新的链表list3,是否纯正这个元素,如果不纯在,把这个元素添加在list3中
 56         for(p3=list3.head;p3;p3=p3->next){
 57             if(p3->value==p->value){
 58                 flag=1;
 59                 break;
 60             }
 61         }
 62         if(flag==0){
 63             addl(&list3, p->value);
 64         }
 65     }
 66     return list3;
 67 }
 68 int main(){
 69     List list1;
 70     int number;
 71     list1.head=NULL;
 72     cout<<"输入第一个链表中的元素,输入-1结束"<<endl;
 73     while(1){
 74         cin>>number;
 75         if(number==-1){
 76             break;
 77         }else{
 78             addl(&list1,number);
 79         }
 80     }
 81     cout<<"第一个链表为"<<endl;
 82     print(&list1);
 83     List list2;
 84     list2.head=NULL;
 85     cout<<"输入第二个链表中的元素,输入-1结束"<<endl;
 86     while(1){
 87         cin>>number;
 88         if(number==-1){
 89             break;
 90         }else{
 91             addl(&list2,number);
 92         }
 93     }
 94     cout<<"第二个链表为"<<endl;
 95     print(&list2);
 96     List ans;
 97     ans=UnionSet(&list1,&list2);
 98     cout<<"生成的集合为"<<endl;
 99     print(&ans);
100     return 0;
101 }

猜你喜欢

转载自www.cnblogs.com/jlbcljb/p/10158914.html