1097 Deduplication on a Linked List
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
题意
第一行给定链表起始结点的地址 h 以及结点总数量 n 。
现在要求我们将该链表中数据重复的结点和数据不重复的结点拆分成两个链表并输出,此题对于正数和负数都相同的数据都算重复数据即数据绝对值不能重复。
思路
具体思路如下:
1.先将结点读入到数组当中,方便后续调用。
2.从起始地址开始往后遍历该链表,并用一个数组 st 来判断是否出现重复的数据,如果该数据是第一次出现,则加入数组 a 中,反之加入数组 b 中。
3.分别输出两个链表,注意地址需要是 5 位数字。
代码
#include<bits/stdc++.h> using namespace std; const int N = 100010; int n, h; int e[N], ne[N]; bool st[N]; int main() { //输入每个结点的信息 cin >> h >> n; for (int i = 0; i < n; i++) { int address, data, next; scanf("%d%d%d", &address, &data, &next); e[address] = data, ne[address] = next; } //将链表中不重数据和重复数据拆分成两个链表 vector<int> a, b; for (int i = h; i != -1; i = ne[i]) { int data = abs(e[i]); if (st[data]) b.push_back(i); else { a.push_back(i); st[data] = true; } } //输出不重数据链表 for (int i = 0; i < a.size(); i++) { printf("%05d %d ", a[i], e[a[i]]); if (i + 1 == a.size()) puts("-1"); else printf("%05d\n", a[i + 1]); } //输出重复数据链表 for (int i = 0; i < b.size(); i++) { printf("%05d %d ", b[i], e[b[i]]); if (i + 1 == b.size()) puts("-1"); else printf("%05d\n", b[i + 1]); } return 0; }