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
Sample Output:
00100 21 23854
23854 -15 99999
99999 -7 -1
00000 -15 87654
87654 15 -1
1 #include <stdio.h> 2 #include <algorithm> 3 #include <set> 4 #include <vector> 5 #include <queue> 6 using namespace std; 7 const int maxn = 100010; 8 9 struct node{ 10 int address; 11 int data; 12 int next; 13 }nodes[maxn]; 14 vector<node> res1; 15 vector<node> res2; 16 int vis[maxn]={0}; 17 int main(){ 18 int st,n; 19 scanf("%d %d",&st,&n); 20 for(int i=0;i<n;i++){ 21 int s,e,d; 22 scanf("%d %d %d",&s,&d,&e); 23 nodes[s].address = s; 24 nodes[s].data = d; 25 nodes[s].next = e; 26 } 27 int root=st; 28 while(root!=-1){ 29 if(vis[abs(nodes[root].data)]!=1){ 30 res1.push_back(nodes[root]); 31 vis[abs(nodes[root].data)]=1; 32 } 33 else{ 34 res2.push_back(nodes[root]); 35 } 36 root=nodes[root].next; 37 } 38 if(!res1.empty()){ 39 printf("%05d %d ",res1[0].address,res1[0].data); 40 for(int i=1;i<res1.size();i++){ 41 printf("%05d\n%05d %d ",res1[i].address,res1[i].address,res1[i].data); 42 } 43 printf("-1\n"); 44 } 45 if(!res2.empty()){ 46 printf("%05d %d ",res2[0].address,res2[0].data); 47 for(int i=1;i<res2.size();i++){ 48 printf("%05d\n%05d %d ",res2[i].address,res2[i].address,res2[i].data); 49 } 50 printf("-1\n"); 51 } 52 }
注意点:普通链表题,把结果存储在两个vector里,再输出就ac了