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 23854Sample Output:
00100 21 23854 23854 -15 99999 99999 -7 -1 00000 -15 87654 87654 15 -1
#include <iostream>
#include <iomanip>
#include <vector>
#include <math.h>
using namespace std;
struct Node
{
int next;
int val;
} node[100010];
int myAbs(int a) {
return a >= 0 ? a : -a;
}
int hashArr[100010];
void print(int rt) {
cout << setfill('0');
while(rt!=-1) {
cout << setw(5) << rt << " " << node[rt].val << " ";
if(node[rt].next != -1) {
cout << setw(5) << node[rt].next << endl;
} else {
cout << node[rt].next << endl;
}
rt = node[rt].next;
}
}
int main() {
int rt, n, pre, next, val, rt2 = -1;
cin >> rt >> n;
for (int i = 0; i < n; ++i)
{
cin >> pre >> val >> next;
node[pre].val = val;
node[pre].next = next;
}
next = node[rt].next;
pre = rt;
hashArr[myAbs(node[rt].val)] = 1;
int pre2, next2;
while(next != -1) {
int tmp = node[next].val >= 0 ? node[next].val: -(node[next].val);
if(hashArr[tmp] == 0) {
hashArr[tmp] = 1;
node[pre].next = next;
pre = next;
} else {
if(rt2 == -1) {
rt2 = next;
pre2 = rt2;
} else {
node[pre2].next = next;
pre2 = next;
}
}
next = node[next].next;
}
node[pre].next = -1;
node[pre2].next = -1;
//cout << "rt = " << rt << " rt2 = " << rt2 << endl;
print(rt);
print(rt2);
return 0;
}
本文介绍了一个算法问题的解决方案:如何从一个含有整数键的单链表中移除具有相同绝对值的重复节点,并将这些移除的节点放入另一个单独的链表中。文章提供了完整的输入输出样例及C++实现代码。
1096

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



