PAT_A1097#Deduplication on a Linked List

Source:

PAT A1097 Deduplication on a Linked List (25 分)

Description:

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 (≤) which is the total number of nodes. The address of a node is a 5-digit nonnegative integer, and NULL is represented by −.

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 1, 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

Keys:

  • 哈希映射

Attention:

  • 注意keep和remo为空时,不能输出-1

Code:

 #include<cstdio>
#include<vector>
#include<cmath>
using namespace std;
const int M=1e5+;
int mp[M]={};
struct node
{
int data;
int adrs,rear;
}link[M],t; int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("Test.txt", "r", stdin);
#endif // ONLINE_JUDGE int first,n;
scanf("%d%d", &first,&n);
for(int i=; i<n; i++)
{
scanf("%d%d%d", &t.adrs,&t.data,&t.rear);
link[t.adrs] = t;
}
vector<int> keep,remo;
while(first != -)
{
if(mp[(int)abs(link[first].data)]==)
{
keep.push_back(first);
mp[(int)abs(link[first].data)]=;
}
else
remo.push_back(first);
first = link[first].rear;
}
for(int i=; i<keep.size(); i++)
{
if(i!=)
printf("%05d\n", keep[i]);
printf("%05d %d ", keep[i], link[keep[i]].data);
}
if(keep.size())
printf("-1\n");
for(int i=; i<remo.size(); i++)
{
if(i!=)
printf("%05d\n", remo[i]);
printf("%05d %d ", remo[i], link[remo[i]].data);
}
if(remo.size())
printf("-1\n"); return ;
}
上一篇:memory allocation


下一篇:PAT A1097 Deduplication on a Linked List (25 分)——链表