Given a singly linked list L L L with integer keys, you are supposed to remove the nodes with duplicated absolute values of the keys. That is, for each value K K K, only the first node of which the value or absolute value of its key equals K K K will be kept. At the mean time, all the removed nodes must be kept in a separate list. For example, given L L 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 ( ≤ 1 0 5 ≤10^5 ≤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 −1 −1.
Then N N 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 0 4 10^4 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
Method:
模拟链表模板,根据标记数组 vis
分别装入两个向量,更新下标并格式化打印。
Solution:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 链表节点
const int maxn = 1e6+10;
struct node{
int address, key, next;
}nod[maxn];
// 标记数组
bool vis[maxn] = {
false};
void print(vector<node> list) {
int sum = list.size();
if(sum != 0){
// 向量不为空时
for (int i = 0; i < sum-1; i++) // 更新下标
list[i].next = list[i+1].address;
list[sum-1].next = -1;
for (int i = 0; i < sum-1; i++) // 格式化打印
printf("%05d %d %05d\n",list[i].address,list[i].key,list[i+1].address);
printf("%05d %d -1\n",list[sum-1].address,list[sum-1].key);
}
}
int main(){
int head = 0, n = 0;
cin >> head >> n;
// 初始化
int address = 0, key = 0, next = 0;
for (int i = 0; i < n; i++) {
cin >> address >> key >> next;
nod[address].address = address;
nod[address].key = key;
nod[address].next = next;
}
// 装入向量
vector<node> list1, list2;
for (head; head != -1; head = nod[head].next) {
if (!vis[ abs( nod[head].key ) ]) {
vis[ abs( nod[head].key ) ] = true;
list1.push_back(nod[head]);
}
else {
list2.push_back(nod[head]);
}
}
print(list1); print(list2);
return 0;
}