本题思路:
遍历整个链表,筛选出两个结构体数组,一个放本体,另一个放副本.通过bool类型数组中的记录判断当前遍历到的key是本体还是副本,再将其放入对应的结构体中.
注意点:可能存在无效结点.
#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<string>
#include<algorithm>
using namespace std;
const int maxn=100010;
bool iscur[10010]={0};
struct node{
int address,key,next;
}nodes[maxn],node1[maxn],node2[maxn];
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt","r",stdin);
#endif
int first,n,idx1=0,idx2=0;
scanf("%d%d",&first,&n);
for(int i=0;i<n;i++){ //初始化输入
int address;
scanf("%d",&address);
scanf("%d%d",&nodes[address].key,&nodes[address].next);
nodes[address].address=address;
}
while(first!=-1){ //遍历整个list,分别筛选到两个结构体数组
int akey=nodes[first].key;
if(akey<0)akey=-akey;
if(iscur[akey]){
node2[idx2++]=nodes[first];
}else{
node1[idx1++]=nodes[first];
iscur[akey]=true;
}
first=nodes[first].next;
}
for(int i=0;i<idx1;i++){ //输出resulting linked list
printf("%05d %d ",node1[i].address,node1[i].key);
if(i==idx1-1){
printf("-1\n");
}else{
printf("%05d\n",node1[i+1].address);
}
}
for(int i=0;i<idx2;i++){ //输出removed list
printf("%05d %d ",node2[i].address,node2[i].key);
if(i==idx2-1){
printf("-1\n");
}else{
printf("%05d\n",node2[i+1].address);
}
}
return 0;
}
算法笔记用的方法实现空间占用少,在一个结构体中实现.
本体结点、副本结点、无效结点三者各自在自己的大范围内,方便通过排序将它们区分开来.