1097 Deduplication on a Linked List

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 (≤10 ​5 ​​ ) 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 10 ​4 ​​ , 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

Sample Output:

00100 21 23854
23854 -15 99999
99999 -7 -1
00000 -15 87654
87654 15 -1



#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<unordered_map>
#include<cmath>
#include<set>
#include<queue>
#include<cstdio>
#include<algorithm>
using namespace std;
struct node{
    int next;
    int data;
}p[100005],q[100005];
unordered_map<int,int>mp;//不自动排序,也可以用上面的q来查询是不是第一个出现的元素(绝对值) 
vector<int>a,b,c;
int main(){
    int N,i,ad,first;
    cin>>first>>N;
    for(i=0;i<N;i++){
        scanf("%d",&ad);
        scanf("%d %d",&p[ad].data,&p[ad].next);
    }   
    while(first!=-1){   //链表排序且去除垃圾结点
        a.push_back(first);
        first=p[first].next;
    }
    for(i=0;i<a.size();i++){
        int x=fabs(p[a[i]].data);
        if(!mp[x]){     //如果mp不为空说明该结点元素的绝对值是第一次出现
            b.push_back(a[i]);
            mp[x]=1;    //标明x这个元素已有了
        }
        else    c.push_back(a[i]);  //c存取绝对值后重复的元素
    }
    for(i=0;i<b.size();i++){    //链b输出
        if(i!=b.size()-1)   printf("%05d %d %05d\n",b[i],p[b[i]].data,b[i+1]);
        else    printf("%05d %d %d\n",b[i],p[b[i]].data,-1);
    }
    for(i=0;i<c.size();i++){    //链c输出
        if(i!=c.size()-1)   printf("%05d %d %05d\n",c[i],p[c[i]].data,c[i+1]);
        else    printf("%05d %d %d\n",c[i],p[c[i]].data,-1);
    }
    return 0;
}