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 (≤10510^5105) 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 10410^4104 , 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
题目大意:题目给出了一个链表,要求将链表中的绝对值重复的节点找出来,将重复的节点重写组成一个链表。
解题思路:使用map<string,pair<int,string>>存读入的链表,使用mp[pre] = make_pair(value, next)快速访问链表节点信息,使用set存访问过的节点的值,将重复和没有重复的值分别push到两个vector,最后将两个vector的内部节点前后连接上。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,string> P;
typedef struct node{
string pre, next;
int val;
node(string pre, string next, int val){
this->pre = pre;
this->next = next;
this->val = val;
}
}node;
map<string, P> mp;
int main(int argc, char const *argv[])
{
string start, addr, next;
int n, val;
cin >> start >> n;
vector<node> nodes, nodes1, nodes2;
for(int i = 0;i < n; i++){
cin >> addr >> val >> next;
nodes.push_back(node(addr, next, val));
mp[addr] = make_pair(val, next);
}
set<int> vals;
while(1){
P v = mp[start];
if(vals.count(abs(v.first)) == 1)
nodes2.push_back(node(start, v.second, v.first));
else if(vals.count(abs(v.first)) == 0){
nodes1.push_back(node(start, v.second, v.first));
vals.insert(abs(v.first));
}
start = v.second;
if(start == "-1")
break;
}
if(nodes1.size() >= 1){
nodes1[nodes1.size()-1].next = "-1";
for(int i = nodes1.size()-2;i >= 0; i--){
nodes1[i].next = nodes1[i+1].pre;
}
}
if(nodes2.size() >= 1){ // 有可能为空
nodes2[nodes2.size()-1].next = "-1";
for(int i = nodes2.size()-2;i >= 0; i--){
nodes2[i].next = nodes2[i+1].pre;
}
}
for(auto it : nodes1){
cout << it.pre << " " << it.val << " " << it.next << endl;
}
for(auto it : nodes2){
cout << it.pre << " " << it.val << " " << it.next << endl;
}
return 0;
}
本文介绍了一种算法,用于从链表中移除绝对值重复的节点,并将其重新组合成一个新链表。通过使用map和set数据结构,算法能够高效地处理这一问题。

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



