L2-002. 链表去重
给定一个带整数键值的单链表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
C++
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
struct lize
{
int a,b,c,d;
};
lize m[101000];
lize n[101000];
lize s[101000];
int w[101000];
int main()
{
int a,b,c,d,e,f,g,i;
scanf("%d %d",&a,&b);
while(b--)
{
scanf("%d",&c);
cin>>m[c].a>>m[c].b;
}
d=0;e=0;
memset(w,0,sizeof(w));
while(1)
{
i=abs(m[a].a);
if(w[i]==0)
{
w[i]=1;
n[d].a=a;
n[d].b=m[a].a;
n[d].c=m[a].b;
d++;
}
else
{
s[e].a=a;
s[e].b=m[a].a;
s[e].c=m[a].b;
if(e!=0)
{
s[e-1].c=m[a].c;
}
e++;
}
a=m[a].b;
if(a==-1)
break;
}
for(c=0;c<d-1;c++)
{
printf("%05d %d %05d\n",n[c].a,n[c].b,n[c+1].a);
}
if(d!=0)
printf("%05d %d -1\n",n[d-1].a,n[d-1].b);
for(c=0;c<e-1;c++)
{
printf("%05d %d %05d\n",s[c].a,s[c].b,s[c+1].a);
}
if(e!=0)
printf("%05d %d -1\n",s[e-1].a,s[e-1].b);
return 0;
}