求集合 用單鏈表表示 的並 交和差運算

2021-09-09 02:25:21 字數 2586 閱讀 4442

#include

#include

typedef char elemtype;

typedef struct lnode linknode; // 宣告單鏈表結點型別

/*------------------------尾插法建立單鏈表---------------------------*/

static void create_list_rear(linknode *&l, elemtype a, int n) // 指標的引用

// 尾結點next域置為null

r->next = null;

}/*------------------------輸出線性表---------------------------*/

static void display_list(linknode *l)

printf("\n");

}/*------------------------銷毀線性表---------------------------*/

static void destroy_list(linknode *&l)

free(pre); // 此時p為null,pre指向尾結點,釋放它

}/*------------------------單鏈表元素遞增排序---------------------------*/

static void sort_list(linknode *&l) // 指標的引用

}/*------------------------求兩個有序集合的並---------------------------*/

// 演算法設計採用二路歸併+尾插法建表思路

static void union_list(linknode *ha, linknode *hb, linknode *&hc)// 指標的引用

else if(pa->data > pb->data)

else

}// 複製餘下的結點

if(pb != null)

pa = pb;

while(pa != null)

tc->next = null;

}/*------------------------求兩個有序集合的交---------------------------*/

// 演算法設計採用二路歸併+尾插法建表思路

static void inter_sect(linknode *ha, linknode *hb, linknode *&hc)// 指標的引用

pa = pa->next;

}tc->next = null;

}/*------------------------求兩個有序集合的差---------------------------*/

// 演算法設計採用二路歸併+尾插法建表思路,c = a - b, c中含有所有屬於集合a而不屬於集合b的元素

static void subs(linknode *ha, linknode *hb, linknode *&hc)

// 若pa結點值不在b中

if(!(pb != null && pb->data == pa->data))

pa = pa->next;

}tc->next = null;

}int main(int argc, char **ar**)

;elemtype b = ;

printf("集合的運算如下:\n");

n = 4;

create_list_rear(ha, a, n);

n = 6;

create_list_rear(hb, b, n);

printf("原集合a:");

display_list(ha);

printf("原集合b:");

display_list(hb);

sort_list(ha);

sort_list(hb);

printf("有序集合a:");

display_list(ha);

printf("有序集合b:");

display_list(hb);

union_list(ha, hb, hc);

printf("集合的並c:");

display_list(hc);

inter_sect(ha, hb, hc);

printf("集合的交c:");

display_list(hc);

#if 1

subs(ha, hb, hc);

printf("集合的差c:");

display_list(hc);

#endif

destroy_list(ha);

destroy_list(hb);

destroy_list(hc);

return 0;

}測試結果:

集合的運算如下:

原集合a:c a e h

原集合b:f h b g d a

有序集合a:a c e h

有序集合b:a b d f g h

集合的並c:a b c d e f g h

集合的交c:a h

集合的差c:c e

資料結構 求集合(單鏈表)的並 交和差運算

求集合 用單鏈表表示 的並 交和差運算 問題描述 該演算法的設計,要求執行結果如下所示 包含三種排序 集合的運算如下 原 集 合a c a e h 原 集 合b f h b g d a 有序集合a a c e h 有序集合b a b d f g h 集合的並c a b c d e f g h 集合的...

python 求兩個list的差集,並集和交集

比如,現在有兩個list型別 a list 1,2,3,4 b list 1,4,5 一.差集 很明顯結果是 2,3,5 下面我們說一下具體方法。方法a.正常法 ret list for item in a list if item not in b list 方法b.簡化版 ret list it...

python 求兩個list的差集,並集和交集

比如,現在有兩個list型別 a list 1,2,3,4 b list 1,4,5 一.差集 很明顯結果是 2,3,5 下面我們說一下具體方法。方法a.正常法 ret list for item in a list if item not inb list 方法b.簡化版 ret list ite...