给定一个带整数键值的链表 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
1.其实这道题没有很复杂,就是每次判断要处理的结点之前是不是出现过,如果出现过那就加入vect1中,如果每出现过那就加入vect2中
2.顺序输出vect2和vect1中的内容即可,注意输出的时候输出next是所在vector中下一个元素的index,末尾输出-1
#include<cstdio>
#include<map>
#include<vector>
#include<iostream>
#include<cstring>
using namespace std;
#define x first
#define y second
map<int,pair<int,int>> hash1,hash2;
vector<pair<int,pair<int,int>>> vect1,vect2;
int st[100010];
int main(){
string line;
int head,n,index,value,next,pre;
scanf("%d%d",&head,&n);
getline(cin,line);
for (int i = 0; i < n; ++i){
getline(cin,line);
sscanf(line.c_str(),"%d%d%d",&index,&value,&next);
hash1[index] = {value,next};
}
int ne = head;
while(ne != -1){
if (hash2.count(-hash1[ne].x) + hash2.count(hash1[ne].x)){
vect1.push_back({ne,{hash1[ne].x,hash1[ne].y}});
}else{
vect2.push_back({ne,{hash1[ne].x,hash1[ne].y}});
hash2[(hash1[ne].x)] = {};
}
ne = hash1[ne].y;
}
for (int i = 0 ; i < vect2.size(); ++i){
if (i + 1 < vect2.size())
printf("%05d %d %05d\n",vect2[i].x,vect2[i].y.x,vect2[i + 1].x);
else if (i + 1 == vect2.size())
printf("%05d %d %d\n",vect2[i].x,vect2[i].y.x,-1);
}
for (int i = 0 ; i < vect1.size(); ++i){
if (i + 1 < vect1.size())
printf("%05d %d %05d\n",vect1[i].x,vect1[i].y.x,vect1[i + 1].x);
else if (i + 1 == vect1.size())
printf("%05d %d %d\n",vect1[i].x,vect1[i].y.x,-1);
}
return 0;
}