利用鍊錶結構實現集合交運算

2021-10-11 02:42:20 字數 1708 閱讀 7789

題目:利用鍊錶資料結構計算集合a和集合b的交

要求:資料元素為字元型,不開闢新的儲存空間,即計算

使用的煉表頭檔案「linklist.h」:

#includeusing namespace std;

templatestruct node

;templateclass linklist

;templatelinklist::linklist()

templatelinklist::~linklist()

head = null;

}templatevoid linklist::createlist(int n)

}templatevoid linklist::insert(int i, t e)

if (!p || j > i - 1)

throw "位置異常";

else }

templatet linklist::delete(int i)

if (!p->next || j > i - 1)

throw "位置異常";

else }

templateint linklist:: locate(t e)

if (p == null)

return 0;

else

return j;

}templatet linklist::getelem(int i)

if (!p || j > i)

throw "位置異常";

else

return p->data;

}templateint linklist::empty()

templatet linklist::prior(t e)

if (p == head)

throw "首元素,無前驅";

else if (q == null)

throw "元素不存在";

else

return p->data;

}templateint linklist::length()

return len;

}templatevoid linklist::listdisplay()

}

思路:建立兩個鍊錶,分別初始化作為集合a和集合b。利用雙重迴圈,外層迴圈從a中拿出元素e,內層迴圈把從a拿出的元素e與b中各元素比較,用變數same判斷b中是否出現和e相同的元素,若發現b中有和e相同的元素,令same+1並退出內層迴圈;下面if判斷same是否為0,若為0,說明該元素不是a與b交集的元素,就將該元素從鍊錶la中刪除。

#include#include"linklist.h"

using namespace std;

typedef char t;

int main()

catch (char *err)

if (la.locate(e))

} while (j <= lb_len);

if (same == 0)

}catch (char *err)

}} cout << "section:" << endl;

la.listdisplay();

cout << endl;

}

需要注意的是,從la中刪除結點後la_len要減1,同時主迴圈變數不能後移,因此i需要-1

用鍊錶實現集合

用鍊錶來表示集合時,鍊錶的中的每個項表示集合的乙個成員,表示集合的鍊錶所占用的空間正比於所表示的集合的大小,而不是正比於全集合的大小,因此,鍊錶可以表示無窮全集合的子集。鍊錶分為無序鍊錶和有序鍊錶兩種型別。以下為有序鍊錶實現 1 typedef struct node link 2struct no...

(C)順序表實現集合運算

1 用陣列a,b,c,e表示集合。假定a b e 輸入陣列a,b,e 全集 輸入資料時要求檢查資料是否重複 集合中的資料要求不重複 要求集合a,b是集合e的子集。2 兩個集合的並運算 把陣列a中各個元素先儲存在陣列c中。將陣列b中的元素逐一與陣列a中的元素進行比較,把不相同的元素新增到陣列c中,陣列...

java利用鍊錶實現棧

在前面,寫了怎麼利用陣列來實現棧,以及動態陣列的利用。今天我們就利用鍊錶的方式來實現棧,我們知道鍊錶儲存資料只要記憶體夠,就可以放足夠多的資料,這也就解決了陣列帶來的弊端。鍊錶類 public class llnode public llnode object data public object ...