/************************************ * * c++程序設計實踐指導 * * 1.5求兩個整數集合並集 * *************************************/ #include <iostream> using namespace std; class SET { struct LinkNode //單鏈表節點數據結構 { int data; LinkNode *next; }; LinkNode *head1, *head2, *head3; //3個單鏈表 int num1, num2, num3; //3個表長 public: SET(int *x, int len1, int *y, int len2) //構造函數,用len1初始化num1,用len2初始化num2 { head1 = new LinkNode; head1->data = -1; head1->next = NULL; head2 = new LinkNode; head2->data = -1; head2->next = NULL; head3 = new LinkNode; head3->data = -1; head3->next = NULL; LinkNode *p1, *p2; p1 = head1; p2 = head2; for(int i = 0; i < len1; i++) { LinkNode *s = new LinkNode; s->data = x[i]; s->next = NULL; p1->next = s; p1 = s; } for(int i = 0; i < len2; i++) { LinkNode *s = new LinkNode; s->data = y[i]; s->next = NULL; p2->next = s; p2 = s; } num1 = len1; num2 = len2; } int notin(int elem, LinkNode *q) //若elem不在以q爲頭節點的單鏈表中則返回1,不然,返回0 { LinkNode *p = q->next; while(p) { if(elem == p->data) return 0; p = p->next; } return 1; } void insert(); //完成求兩集合並集的功能 void desert(); //完成求兩集合交集的功能 void show() { LinkNode *p = head3->next; while(p) { cout << p->data << " "; p = p->next; } cout << endl; cout << "新的集合元素個數是 :" << num3 <<endl; } }; void SET::insert() //求兩集合並集 { LinkNode *p1 = head1->next; LinkNode *p2 = head2->next; LinkNode *p, *q; q = head3; while(p1) //先將單鏈表1中的元素複製到單鏈表3中 { p = new LinkNode; p->data = p1->data; p->next = NULL; q->next = p; q = p; p1 = p1->next; } num3 = num1; while(p2) //將在單鏈表2中而不在單鏈表1中的元素複製到單鏈表3中 { if(notin(p2->data, head3)) { p = new LinkNode; p->data = p2->data; p->next = NULL; q->next = p; q = p; ++num3; } p2 = p2->next; } } void SET::desert() //求交集 { LinkNode *p1 = head1->next; LinkNode *p2 = head2->next; LinkNode *p, *q; q = head3; num3 = 0; while(p2) //將單鏈表2與單鏈表1比較,二者均有的元素加入單鏈表3中 { if(notin(p2->data,head1) == 0) { p = new LinkNode; p->data = p2->data; p->next = NULL; q->next = p; q = p; ++num3; } p2 = p2->next; } } int main() { int s1[] = {1,3,5,7,9}; int s2[] = {2,4,6,9}; SET set(s1, sizeof(s1)/sizeof(s1[0]), s2, sizeof(s2)/sizeof(s2[0])); cout << "並集:"; set.insert(); set.show(); cout << "交集:"; set.desert(); set.show(); system("pause"); return 0; }