求两个有序单链表的并交集
求并集————————————————————————————
#include <iostream> #include "./List.h"//利用我们自己实现的单链表List using namespace std; void PrintList(List L) { if(NULL == L) return; Position pos = First(L); cout<<"List L:"; while(NULL != pos) { cout<<Retrieve(pos)<<"->"; pos = pos->next; } cout<<"NULL"<<endl;; } List UnionOfTwoLists(List list1, List list2) { if(NULL == list1 && NULL == list2) return NULL; Position p1 = First(list1), p2 = First(list2); List out = CreateEmptyList(); while(NULL != p1 && NULL != p2) { if(Retrieve(p1) <= Retrieve(p2)) { PushBack(Retrieve(p1), out); p1 = p1->next; } else { PushBack(Retrieve(p2), out); p2 = p2->next; } } if(NULL == p1) { while(NULL != p2) { PushBack(Retrieve(p2), out); p2 = p2->next; } } else if(NULL == p2) { while(NULL != p1) { PushBack(Retrieve(p1), out); p1 = p1->next; } } return out; } int main(int argc, char const *argv[]) { List list1 = CreateEmptyList(); List list2 = CreateEmptyList(); for (int i = 0; i < 10; ++i) PushBack(i, list1); for (int i = 0; i < 20; i += 2) PushBack(i, list2); PrintList(list1); PrintList(list2); List res = UnionOfTwoLists(list1, list2); PrintList(res); return 0; }
求交集——————————————————————————————
#include <iostream> #include "./List.h"//利用我们自己实现的单链表List using namespace std; void PrintList(List L) { if(NULL == L) cout<<"Error List L is NULL!!!"<<endl; Position pos = First(L); cout<<"List L:"; while(NULL != pos) { cout<<Retrieve(pos)<<"->"; pos = pos->next; } cout<<"NULL"<<endl;; } List IntersectionOfTwoLists(List list1, List list2) { if(NULL == list1 && NULL == list2) return NULL; Position p1 = First(list1); List out = CreateEmptyList(); while(NULL != p1) { Position tmp = Find(Retrieve(p1), list2); if(NULL != tmp) PushBack(Retrieve(tmp), out); p1 = p1->next; } return out; } int main(int argc, char const *argv[]) { List list1 = CreateEmptyList(); List list2 = CreateEmptyList(); for (int i = 0; i < 20; ++i) PushBack(i, list1); for (int i = 0; i < 20; i += 2) PushBack(i, list2); PrintList(list1); PrintList(list2); List res = IntersectionOfTwoLists(list1, list2); PrintList(res); return 0; }