7-8 連結串列去重(25 分)
阿新 • • 發佈:2019-01-28
給定一個帶整數鍵值的連結串列 L,你需要把其中絕對值重複的鍵值結點刪掉。即對每個鍵值 K,
只有第一個絕對值等於 K 的結點被保留。同時,所有被刪除的結點須被儲存在另一個連結串列上。
例如給定 L 為 21→-15→-15→-7→15,你需要輸出去重後的連結串列 21→-15→-7,還有被刪除的連結串列 -15→15。
輸入格式:
輸入在第一行給出 L 的第一個結點的地址和一個正整數 N(≤10
5
,為結點總數)。一個結點的地址是非負的 5 位整數,空地址 NULL 用 -1 來表示。
隨後 N 行,每行按以下格式描述一個結點:
地址 鍵值 下一個結點
其中地址是該結點的地址,鍵值是絕對值不超過10
4
的整數,下一個結點是下個結點的地址。
輸出格式:
首先輸出去重後的連結串列,然後輸出被刪除的連結串列。每個結點佔一行,按輸入的格式輸出。
輸入樣例:
00100 5
99999 -7 87654
23854 -15 00000
87654 15 -1
00000 -15 99999
00100 21 23854
輸出樣例:
00100 21 23854
23854 -15 99999
99999 -7 -1
00000 -15 87654
87654 15 -1
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <cstdlib> using namespace std; struct node{ int data; int next; }list[100005]; int main() { int head, n; scanf("%d%d",&head,&n); while(n--) { int adress; scanf("%d",&adress); scanf("%d%d",&list[adress].data,&list[adress].next); } int ans[100005], k1 = 0; int res[100005], k2 = 0; bool vis[100005]; memset(vis, 0, sizeof(vis)); //把bool型別的陣列全值為0 int p = head; //找到頭節點 while(p != -1) { int m = abs(list[p].data); if(!vis[m]) //把資料域出現的數放在vis陣列中下標為m所對應的值中,記錄下來置為1 { //同把這個地址p存進ans中,然後比較,有重複的話就把這個地址p放到res陣列中 ans[k1++] = p; vis[m] = 1; } else { res[k2++] = p; } p = list[p].next; } printf("%05d", head); for(int i = 1; i < k1; i++) { printf(" %d %05d\n%05d", list[ans[i-1]].data, ans[i], ans[i]); } printf(" %d -1\n", list[ans[k1-1]].data); if(k2 > 0) { printf("%05d", res[0]); for(int i = 1; i < k2; i++) { printf(" %d %05d\n%05d", list[res[i-1]].data, res[i], res[i]); } printf(" %d -1", list[res[k2-1]].data); } return 0; }