陣列模擬連結串列運作!!L2-002. 連結串列去重
阿新 • • 發佈:2019-01-22
給定一個帶整數鍵值的單鏈表L,本題要求你編寫程式,刪除那些鍵值的絕對值有重複的結點。即對任意鍵值K,只有鍵值或其絕對值等於K的第一個結點可以被保留。同時,所有被刪除的結點必須被儲存在另外一個連結串列中。例如:另L為21→-15→-15→-7→15,則你必須輸出去重後的連結串列21→-15→-7、以及被刪除的連結串列-15→15。
輸入格式:
輸入第一行包含連結串列第一個結點的地址、以及結點個數N(<= 105 的正整數)。結點地址是一個非負的5位整數,NULL指標用-1表示。
隨後N行,每行按下列格式給出一個結點的資訊:
Address Key Next
其中Address是結點的地址,Key
輸出格式:
首先輸出去重後的連結串列,然後輸出被刪除結點組成的連結串列。每個結點佔一行,按輸入的格式輸出。
輸入樣例: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<stdio.h> #include<string.h> #include<algorithm> using namespace std; int vis[1001100]; int mapp[1001100],mappp[1001100]; int keep1[1001100],keep2[1001100]; int main() { int a,b,c; int vv1=0,vv2=0; memset(vis,0,sizeof(vis)); int m,n; scanf("%d%d",&m,&n); for(int i=0;i<n;i++) { scanf("%d%d%d",&a,&b,&c); mapp[a]=b; mappp[a]=c; } int pp; pp=m; while(mappp[pp]!=-1) { int flag=0; if(mapp[pp]<0) { flag=1; mapp[pp]=-mapp[pp]; } if(vis[mapp[pp]]==0) { if(vv2>0) keep2[vv2-1]=mappp[pp]; if(flag==1) { keep1[vv1++]=pp; keep1[vv1++]=-mapp[pp]; keep1[vv1++]=mappp[pp]; vis[mapp[pp]]=1; pp=mappp[pp]; } else { keep1[vv1++]=pp; keep1[vv1++]=mapp[pp]; keep1[vv1++]=mappp[pp]; vis[mapp[pp]]=1; pp=mappp[pp]; } } else { keep1[vv1-1]=mappp[pp]; if(flag==1) { keep2[vv2++]=pp; keep2[vv2++]=-mapp[pp]; keep2[vv2++]=mappp[pp]; pp=mappp[pp]; } else { keep2[vv2++]=pp; keep2[vv2++]=mapp[pp]; keep2[vv2++]=mappp[pp]; pp=mappp[pp]; } } } int flag1=0; if(mapp[pp]<0) { flag1=1; mapp[pp]=-mapp[pp]; } if(vis[mapp[pp]]==1) { if(flag1==0) { keep2[vv2++]=pp; keep2[vv2++]=mapp[pp]; keep2[vv2++]=mappp[pp]; keep1[vv1-1]=-1; } else { keep2[vv2++]=pp; keep2[vv2++]=-mapp[pp]; keep2[vv2++]=mappp[pp]; keep1[vv1-1]=-1; } } else { if(!flag1) { keep1[vv1++]=pp; keep1[vv1++]=mapp[pp]; keep1[vv1++]=mappp[pp]; keep2[vv2-1]=-1; } else { keep1[vv1++]=pp; keep1[vv1++]=-mapp[pp]; keep1[vv1++]=mappp[pp]; keep2[vv2-1]=-1; } } for(int i=1;i<=vv1;i++) { if(keep1[i-1]==-1) printf("-1"); else if(i%3==1||i%3==0) printf("%05d",keep1[i-1]); else if(i%3==2) printf("%d",keep1[i-1]); if(i%3) printf(" "); else printf("\n"); } for(int i=1;i<=vv2;i++) { if(keep2[i-1]==-1) printf("-1"); else if(i%3==1||i%3==0) printf("%05d",keep2[i-1]); else if(i%3==2) printf("%d",keep2[i-1]); if(i%3) printf(" "); else printf("\n"); } return 0; }