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.
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.
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.
00100 5
99999 -7 87654
23854 -15 00000
87654 15 -1
00000 -15 99999
00100 21 23854
00100 21 23854
23854 -15 99999
99999 -7 -1
00000 -15 87654
87654 15 -1
1、设计两个vector分别存储(其绝对值)未出现过的key,以及(其绝对值)出现过的key。
2、用一个bool node[100000]
一维数组来记录每一个key(的绝对值)是否出现过,下标即key(的绝对值)。
3、最后,遍历两个vector即可。
4、特别注意,考虑一种极端情况,如果所有结点的key的绝对值都相同,那么最终链表中将只有一个结点。
第一种写法没有考虑链表中只有一个结点的情况,因此f[i+1]是空的,会导致有一个用例无法通过(发生段错误),第二种写法才是正确的!
//第一种写法
for(int i = 0; i < f.size()-1; i++){
printf("%05d %d %05d\n", f[i].addr,f[i].key,f[i+1].addr);
}
printf("%05d %d -1\n", f[f.size()-1].addr,f[f.size()-1].key);
//第二种写法
for(int i = 0; i < f.size(); i++){
if(i == f.size()-1)
printf("%05d %d -1\n", f[i].addr,f[i].key);
else
printf("%05d %d %05d\n", f[i].addr,f[i].key,f[i+1].addr);
}
代码如下
#include
#include
#include
using namespace std;
struct NODE{
int addr,key,next;
}node[100000];
vector<NODE> f,e;
bool exist[10001];
int main()
{
int start,n,addr,key,next;
scanf("%d%d", &start,&n);
for(int i = 0; i < n; i++){
scanf("%d%d%d", &addr,&key,&next);
node[addr] = {addr,key,next};
}
for(int i = start; i != -1; i = node[i].next){
if(exist[abs(node[i].key)]==false){
exist[abs(node[i].key)] = true;
f.push_back(node[i]);
}else{
e.push_back(node[i]);
}
}
for(int i = 0; i < f.size(); i++){
if(i == f.size()-1)
printf("%05d %d -1\n", f[i].addr,f[i].key);
else
printf("%05d %d %05d\n", f[i].addr,f[i].key,f[i+1].addr);
}
for(int i = 0; i < e.size(); i++){
if(i == e.size()-1)
printf("%05d %d -1\n", e[i].addr,e[i].key);
else
printf("%05d %d %05d\n", e[i].addr,e[i].key,e[i+1].addr);
}
return 0;
}