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 (≤10e5) 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 10e4, 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
Note
- 题意,将链表中值的绝对值不是第一次出现的所有元素删除,排在后面输出
- 思路: 读入所有节点记录在nodes里(id, next),从start开始,visit过abs(id)的就放在另一个链表里
- 错误
a. 停止的条件不能数个数,而是找-1,因为可能有无效节点
b. 特殊处理的-1节点要注意没节点的情况
Code
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
const int maxn = 1e6 + 100;
struct node{
int id;
int next;
}nodes[maxn];
node deleted[maxn];
int visited[maxn] = {0}, check[maxn];
int main(){
string s;
int num, start, cnt = 0,cnt1 = 0,last_save, deleted_start, deleted_last ;
cin >> start >> num;
for(int i = 0; i < num; i++){
int address, id,temp;
cin >> address >> id >> s;
if(s[0] == 'N') temp = -1;
else temp = stoi(s);
nodes[address].id = id;
nodes[address].next = temp;
}
int temp = start;
for(int i = 0; temp != -1; i++){
if(visited[abs(nodes[temp].id)] == 0){
visited[abs(nodes[temp].id)] = 1;
if(cnt != 0) nodes[last_save].next = temp;
last_save = temp; //记录上一个没重复的地址
cnt ++;
}
else{
if(cnt1 == 0) deleted_start = temp;
else deleted[deleted_last].next = temp;
deleted_last = temp;
deleted[temp].id = nodes[temp].id;
cnt1++;
}
temp = nodes[temp].next;
}
temp = start;
for(int i = 0; i < cnt - 1 ; i++){
printf("%05d %d %05d\n", temp, nodes[temp].id , nodes[temp].next );
temp = nodes[temp].next;
}
if(cnt > 0)
printf("%05d %d -1\n", temp, nodes[temp].id );
temp = deleted_start;
for(int i = 0; i < cnt1 - 1 ; i++){
printf("%05d %d %05d\n", temp, deleted[temp].id , deleted[temp].next );
temp = deleted[temp].next;
}
if(cnt1 > 0)
printf("%05d %d -1\n", temp, deleted[temp].id );
return 0;
}