数据结构题目005

    科技2024-12-13  29

    利用静态链表实现集合运算(A-B)U(B-A):从键盘输入集合元素。

    以下为相关代码:

    #include <stdio.h> #include <stdlib.h> typedef int elementtype; #define maxsize 100 typedef struct spacestr{ elementtype element; int next; }spacestr; //结点类型 spacestr SPACE[maxsize] ;//存储池 typedef int position,cursor; cursor av;//游标变量,标识线性表 void Initialize(spacestr *SPACE, int *av) { int j; // 依次链接池中结点 for (j=0; j<maxsize-1; j++) { SPACE[j].next = j+1; SPACE[j].element = -1; } // 最后一个接点指针域为空 SPACE[j].next = -1; // 标识线性表 *av=0; } cursor Malloc_SL(spacestr *SPACE, int *av) // q=new spacestr ; { cursor q; if (SPACE[*av].next ==-1) q=-1; else { q= SPACE[*av].next ; //q=11 SPACE[*av].next = SPACE[q].next; } //av=12 } return q; }/*从池中删除*/ //delete q; void Free_SL(cursor q, int *av) { SPACE[q].next =SPACE[*av].next ; SPACE[*av].next = q ; }/*放回池中*/ void Insert ( elementtype x, position p, spacestr *SPACE ) { position q; q = Malloc_SL( SPACE , &p ); SPACE[q].element = x ; SPACE[q].next = SPACE[p].next ; SPACE[p].next = q ; } void Delete ( position p, spacestr *SPACE ) { position q; if ( SPACE[p].next != -1 ) { q = SPACE[p].next ; SPACE[p].next = SPACE[q].next ; Free_SL( q , &p) ; } } int main() { spacestr A[maxsize],B[maxsize],C[maxsize],D[maxsize]; int ai = 0,bi = 0,ci = 0,di = 0; Initialize(A,&av); Initialize(B,&av); int i = 0; char result = 'f'; do{ int num; printf("请先输入A集合元素:"); scanf("%d",&num); getchar(); Insert(num,i,A); ai++; i++; printf("还想继续输入吗?(t--继续,f--停止)"); scanf("%c",&result); }while(result == 't' ); i = 0; result = 'f'; do{ int num; printf("请先输入B集合元素:"); scanf("%d",&num); getchar(); Insert(num,i,B); bi++; i++; printf("还想继续输入吗?(t--继续,f--停止)"); scanf("%c",&result); }while(result == 't' ); for (int i = 1; i <= ai; i++) { for (int j = 1; j <= bi; j++) { if (A[i].element == B[j].element) { C[ci].element = A[i].element; ci++; } } } for (int i = 1; i <= ai; i++) { for (int j = 0; j < ci; j++) { if (A[i].element == C[j].element) { A[i].element = -1; } } } for (int i = 1; i <= bi; i++) { for (int j = 0; j < ci; j++) { if (B[i].element == C[j].element) { B[i].element = -1; } } } for (int i = 1; i <= ai; i++) { if (A[i].element != -1) { D[di].element = A[i].element; di++; } } for (int i = 1; i <= bi; i++) { if (B[i].element != -1) { D[di].element = B[i].element; di++; } } printf("A集合和B集合的对称差为:\n"); for (int i = 0; i < di; i++) { printf("%d\t",D[i].element); } printf("\n"); system("pause"); return 0; }
    Processed: 0.010, SQL: 8