习题3.4 & 3.5: 求两链表的交集和并集
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<stdio.h> #include<stdlib.h> struct Node; typedef struct Node *PtrToNode; typedef PtrToNode List; typedef PtrToNode Position; struct Node{ ElementType Ele; PtrToNode Next; }; Position First( List L ) { return L->Next; } Position Next( List L, Position p ) { return p->Next; } List CreateAndMakeEmpty( List L ) { L = malloc( sizeof( struct Node ) ); if( L == NULL ) Error("out of space "); L->Next = NULL; return L; } void Insert( Position p, ElementType X ) { Position TmpCell; TmpCell = malloc( sizeof( struct Node ) ); if( TmpCell == NULL ) Error("out of space "); TmpCell->Ele = X; TmpCell->Next = p->Next; p->Next = TmpCell; } List FindSimilar( List L1, List L2 ) { Position L1Pos,L2Pos,LresPos; List Lres; CreateAndMakeEmpty( Lres ); LresPos = Lres; L1Pos = First(L1); L2Pos = First(L2); while( L1Pos != NULL && L2Pos != NULL ) { if( L1Pos->Ele > L2Pos->Ele ) next( L2, L2Pos ); else if( L1Pos->Ele < L2Pos->Ele ) next( L1, L1Pos ) else { Insert( LresPos, L1Pos->Ele ); LresPos = LresPos->Next; L1Pos = next( L1, L1Pos ); L2Pos = next( L2, L2Pos ); } } } void PrintList( List Lres ) { Position p; p = First( Lres ); while( p != NULL ) { printf("%?",p->Ele); p = p->Next; } } List GetUnion( List L1, List L2 ) { ElementType InsertEle; List Lres; Position L1Pos,L2Pos,LresPos; L1Pos = First( L1 ); L2Pos = First( L2 ); Lres = CreateAndMakeEmpty( Lres ); LresPos = Lres; while( L1Pos != NULL && L2Pos != NULL ) { if( L1Pos->Ele < L2Pos->Ele ) { InsertEle = L1Pos->Ele; L1Pos = next( L1, L1pos ); } else if( L1Pos->Ele > L2Pos->Ele ) { InsertEle = L2Pos->Ele; L2Pos = next( L2, L2Pos ); } else { InsertEle = L1Pos->Ele; L1Pos = next( L1, L1Pos ); L2Pos = next( L2, L2Pos ); } Insert( LresPos, InsertEle ); LresPos = next( Lres, LresPos ); } while( L1Pos != NULL ) { InsertEle = L1Pos->Ele; Insert( LresPos, InsertEle ); LresPos = next( Lres, LresPos ); L1Pos = next( L1Pos ); } while( L2Pos != NULL ) { InsertEle = L2Pos->Ele; Insert( LresPos, InsertEle ); LresPos = next( Lres, LresPos ); L2Pos = next( L2, L2Pos ); } printList(); }