資料結構——連結串列求兩集合的交集
阿新 • • 發佈:2018-12-10
#include <stdio.h> #include <malloc.h> typedef struct Node { int data; struct Node *next; }LNode,*LinkList; LNode *CreateList() { // 建立單迴圈連結串列,返回連結串列頭 LNode *head,*p; int i,n; scanf("%d",&n); head = p = (LNode *)malloc(sizeof(LNode)); // 專用頭結點 head->data = 0; for(i = 0; i < n; ++i) { p->next = (LNode *)malloc(sizeof(LNode)); scanf("%d",&p->next->data); p = p->next; } p->next = head; return head; } LNode *MutualAgg(LNode *A,LNode *B) { // A∩B LNode *C,*pa,*pb,*pc,*qc; C = pc = (LNode *)malloc(sizeof(LNode)); pc->data = 0; pa = A->next; pb = B; while(pa != A) { pb = B->next; while(pb != B) { if(pb->data == pa->data) { qc = (LNode *)malloc(sizeof(LNode)); qc->data = pb->data; pc->next = qc; pc = qc; } pb = pb->next; } pa = pa->next; } pc->next = C; return C; } void PrintList(LNode *head) { LNode *p = head->next; short counter = 0; while(p != head) { if(counter && counter%10 == 0) printf("\n"); printf("%d ",p->data); counter++; p = p->next; } if(counter % 10) printf("\n"); } void freeheap(LNode *head) { LNode *p,*q; p = head; q = p->next; while(q != head) { p = q; q = p->next; free(p); } free(head); } int main() { LNode *A,*B,*C,*D,*E; A = CreateList(); B = CreateList(); C = MutualAgg(A,B); PrintList(C); freeheap(A); freeheap(B); freeheap(C); printf("\n\n"); return 0; }