给定一个带整数键值的单链表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是绝对值不超过104的整数,Next是下一个结点的地址。
输出格式:
首先输出去重后的链表,然后输出被删除结点组成的链表。每个结点占一行,按输入的格式输出。
输入样例: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; }