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 (≤) which is the total number of nodes. The address of a node is a 5-digit nonnegative integer, and NULL is represented by −.
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 1, 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
#include <iostream>
#include <unordered_map>
#include <cmath>
using namespace std;
struct Node
{
int addr, val;
Node(int a, int b) :addr(a), val(b) {}
};
struct List
{
Node val;
List* next;
List(Node a) :val(a), next(nullptr) {}
};
int N, head, addr1, addr2, val, numbers[] = { };
int main()
{
cin >> head >> N;
if (head == -)//切记,此时有一个测试例子是头结点为-1,那么什么也不输出
return ;
unordered_map<int, pair<int, int>>map;
for (int i = ; i < N; ++i)
{
cin >> addr1 >> val >> addr2;
map[addr1] = make_pair(val, addr2);
}
//将链表组合起来
List* resHead = new List(Node(, -));
List* delHead = new List(Node(, -));
List* p = resHead;
while (head != -)
{
List* q = new List(Node(head, map[head].first));
p->next = q;
p = q;
head = map[head].second;
}
List* pre = resHead, *delP = delHead;
p = pre->next;
while (p != nullptr)
{
if (numbers[abs(p->val.val)] == )
{
pre->next = p->next;//删除
List* q = new List(Node(p->val.addr, p->val.val));
delP->next = q;
delP = q;
delete p;
p = pre->next;
}
else
{
numbers[abs(p->val.val)]++;
pre = p;
p = pre->next;
}
}
p = resHead->next;
while (p != nullptr)
{
printf("%05d %d ", p->val.addr, p->val.val);
p = p->next;
if (p == nullptr)
printf("%d\n", -);
else
printf("%05d\n", p->val.addr);
}
p = delHead->next;
while (p != nullptr)
{
printf("%05d %d ", p->val.addr, p->val.val);
p = p->next;
if (p == nullptr)
printf("%d\n", -);
else
printf("%05d\n", p->val.addr);
}
return ;
}