1. 程式人生 > >2017年吉林大學考研初試專業課966 第七題

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 }