L2-002 鏈表去重 (25 分) 給定一個帶整數鍵值的鏈表 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 <bits/stdc++.h> using namespace std; #define N 100010 #define P pair<int,int> #define mod 1000000007 #define ll long long struct Node{ int val,next; Node(){ } Node(int val,int next):val(val),next(next){ } }e[N]; int a1[N],a2[N],vis[N]; int id,ID,n; int main() { scanf("%d%d",&ID,&n); for(int i =0;i<n;i++){ scanf("%d",&id); scanf("%d%d",&e[id].val,&e[id].next); } int cnt1=0,cnt2=0; for(int i =ID;i!=-1;i=e[i].next){ if(!vis[abs(e[i].val)]){ vis[abs(e[i].val)] =1; a1[cnt1++] = i; } else{ a2[cnt2++] =i; } } printf("%05d %d ",ID,e[ID].val); for(int i =1;i<cnt1;i++){ printf("%05d\n",a1[i]); printf("%05d %d ",a1[i],e[a1[i]].val); } printf("-1\n"); if(cnt2){//可能爲0 printf("%05d %d ",a2[0],e[a2[0]].val); for(int i =1;i<cnt2;i++){ printf("%05d\n",a2[i]); printf("%05d %d ",a2[i],e[a2[i]].val); } printf("-1\n"); } return 0; }