1097 Deduplication on a Linked List (25 分)
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
有了前几题的铺垫,此题写得轻松多了,%05d输出 无效结点啥的。。
唯一需要注意的是:absolute value 是绝对值的意思,从测试样例也可以看出来
#include<iostream>
#include<vector>
using namespace std;
struct Node {
int address, key, next;
}node[100010], ans[100010];
int h, n, Hash[10010] = { 0 };
int main() {
//freopen("in.txt", "r", stdin);
cin >> h >> n;
int add, key, next;
while (n--) {
cin >> add >> key >> next;
node[add].address = add;
node[add].key = key;
node[add].next = next;
}
n = 0;
for (int i = h;i != -1;i = node[i].next) {//遍历一遍 过滤无效结点
ans[n++] = node[i];//address都记录下来了 可以从0开始编号了 这样下面也少了写链表遍历的复杂代码
}
vector<Node> ve1, ve2;
for (int i = 0;i<n;i++) {
if (Hash[abs(ans[i].key)] == 0) {
ve1.push_back(ans[i]);//瞎写 此处要遍历的是筛选后的ans 不是node了
Hash[abs(ans[i].key)] = 1;
}
else ve2.push_back(ans[i]);
}
for (int i = 0;i<ve1.size();i++) {
printf("%05d %d ", ve1[i].address, ve1[i].key);
if (i != ve1.size() - 1) printf("%05d\n", ve1[i + 1].address);
else printf("-1\n");
}
for (int i = 0;i<ve2.size();i++) {
printf("%05d %d ", ve2[i].address, ve2[i].key);
if (i != ve2.size() - 1) printf("%05d\n", ve2[i + 1].address);
else printf("-1\n");
}
return 0;
}