静态链表实现 取巧+思路清晰 但是时间复杂度比较高 可以优化insert
Given a singly linked list L with integer keys, you are supposed to remove the nodes with duplicated absolute values of the keys. That is, for each value K, only the first node of which the value or absolute value of its key equals K will be kept. At the mean time, all the removed nodes must be kept in a separate list. For example, given L being 21→-15→-15→-7→15, you must output 21→-15→-7, and the removed list -15→15.
Input Specification:
Each input file contains one test case. For each case, the first line contains the address of the first node, and a positive N (≤105) which is the total number of nodes. The address of a node is a 5-digit nonnegative integer, and NULL is represented by −1.
Then N lines follow, each describes a node in the format:
Address Key Next
where Address
is the position of the node, Key
is an integer of which absolute value is no more than 104, and Next
is the position of the next node.
Output Specification:
For each case, output the resulting linked list first, then the removed list. Each node occupies a line, and is printed in the same format as in the input.
Sample Input:
00100 5
99999 -7 87654
23854 -15 00000
87654 15 -1
00000 -15 99999
00100 21 23854
代码:
#include<bits/stdc++.h>
using namespace std;
int main(){
int head,n;
cin>>head>>n;
int node[100010];//存储地址的key值
int next[100010];//存储下一个地址的值
for(int i=0;i<n;i++){
int address,data,Next;
scanf("%d %d %d",&address,&data,&Next);
node[address]=data;
next[address]=Next;
}
vector<int> v;//v存储遍历的地址 可以看做key的映射
for(int i=head;i!=-1;i=next[i]){
v.push_back(i);
}
set<int> se;//se用来存储绝对值
vector<int> d;//d用来存储重复的值的地址
for(int i=0;i<v.size();i++){
if(se.find(abs(node[v[i]]))!=se.end()){//如果不是第一个
d.push_back(v[i]);//有重复 存进d
v.erase(v.begin()+i);//删除该值
i=i-1;//因为删除了 所以i下标-1 否则会跳过一位
}
else{
se.insert(abs(node[v[i]]));//是第一个值 插入集合se
}
}
//输出
for(int i=0;i<v.size();i++){
if(i!=v.size()-1)printf("%05d %d %05d\n",v[i],node[v[i]],v[i+1]);
else printf("%05d %d -1\n",v[i],node[v[i]]);
}
for(int k=0;k<d.size();k++){
if(k!=d.size()-1)printf("%05d %d %05d\n",d[k],node[d[k]],d[k+1]);
else printf("%05d %d -1",d[k],node[d[k]]);
}
return 0;
}