1097 Deduplication on a Linked List (25 point(s))
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
链表、STL(set/vector)的使用。
思路:
set<int> s记录已经在链表中的元素的绝对值,v和u分别记录在链表中的和不在链表中的元素的地址。根据给出的头结点地址,遍历整个链表,如果该地址的元素的绝对值还不在s中,说明在v中,否则在u中。
然后根据得到的v和u按照格式输出。
注意点:u也是需要输出的,认真读题很重要。
#include<iostream>
#include<set>
#include<vector>
#include<cstring>
#include<cmath>
using namespace std;
const int MAX = 1e5+7;
int data[MAX];
int nextAdd[MAX];
int main(void){
int N,root;cin>>root>>N;
int address,key,next;
for(int i=0;i<N;i++){
cin>>address>>key>>next;
data[address]=key;
nextAdd[address]=next;
}
set<int> s;
vector<int> v;
vector<int> u;
while(root!=-1){
if(s.find(abs(data[root]))==s.end()){
v.push_back(root);
s.insert(abs(data[root]));
}
else{
u.push_back(root);
}
root = nextAdd[root];
}
for(int i=0;i<v.size();i++){
if(i!=v.size()-1)printf("%05d %d %05d\n",v[i],data[v[i]],v[i+1]);
else printf("%05d %d -1\n",v[i],data[v[i]]);
}
for(int i=0;i<u.size();i++){
if(i!=u.size()-1)printf("%05d %d %05d\n",u[i],data[u[i]],u[i+1]);
else printf("%05d %d -1\n",u[i],data[u[i]]);
}
return 0;
}
本文介绍了一个关于链表去重的问题,通过遍历链表并利用STL set来记录已出现的绝对值,实现对链表中重复绝对值元素的去除,并将去除的元素保存在另一个链表中。最后,文章提供了完整的C++代码实现。
1562

被折叠的 条评论
为什么被折叠?



