1097 Deduplication on a Linked List (25)(25 分)
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
Analysis :
a conventioal problem,I have discussed such kind problem in another blog. use array to store the linkedlist .
it is evident that you shoud count the situaiton in if there is no duplication.
C++:
#include<stdio.h>
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<queue>
#include<set>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct inf{
int data;
int next;
};
struct inf list[100000];
struct inf removed[100000];
int vis[10000];
int main()
{
freopen("1097 Deduplication on a Linked List.txt","r",stdin);
int firstadd,n,count=0,last;
cin>>firstadd>>n;
while(n--){
int add,data,next;
cin>>add>>data>>next;
list[add].data=data;
list[add].next=next;
}
int tempadd,flag=1,removefirstadd=-1;
printf("%05d %d ",firstadd,list[firstadd].data);
vis[abs(list[firstadd].data)]=1;
tempadd=list[firstadd].next;
while(tempadd!=-1){
if(vis[abs(list[tempadd].data)]==0){
vis[abs(list[tempadd].data)]=1;
printf("%05d\n%05d %d ",tempadd,tempadd,list[tempadd].data);
}
else{
if(flag){//solve the first duplication
removefirstadd=tempadd;
last=tempadd;
flag=0;
}
//last is the address of the last duplication
removed[last].next=tempadd;
removed[tempadd].data=list[tempadd].data;
last=tempadd;
count++;
}
tempadd=list[tempadd].next;
}
if(removefirstadd!=-1){
printf("-1\n%05d %d ",removefirstadd,list[removefirstadd].data);
tempadd=removed[removefirstadd].next;
int i=0;
while(i<count-1){
printf("%05d\n%05d %d ",tempadd,tempadd,removed[tempadd].data);
tempadd=removed[tempadd].next;
i++;
}
}
cout<<-1<<endl;
return 0;
}