PAT - 甲级 - 1097. Deduplication on a Linked List (25)(链表)

时间:2021-10-21 19:47:03

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

给定条件:
1.n个节点的地址,值,下一个节点地址
2.链表的第一个节点的地址

要求:
1.删除链表中“重复”出现的元素(如果该节点值的绝对值和之前的某一节点的值的绝对值相等就称之为“重复”)
2.输出删除“重复”出现的元素后的链表
3.将删除的元素组成新的链表删除

求解:
1.申明两个容器
2.分别将不删除的元素和要删除的元素放在两个容器中
3.遍历输出

注意:
1.一共输出两个链表


#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;

struct Node {
int ad, val, nextAd;
} node[100010];

vector<Node> result, removed;

bool vis[100010];
int start, n;
int ad, val, nextAd;

int main() {
fill(vis, vis+100010, false);

scanf("%d%d", &start, &n);

for(int i = 0; i < n; i++) {
scanf("%d%d%d", &ad, &val, &nextAd);
node[ad].ad = ad;
node[ad].val = val;
node[ad].nextAd = nextAd;
}

for(int i = start; i != -1; i = node[i].nextAd) {
int absVal = abs(node[i].val);

if(vis[absVal] == false) {
result.push_back(node[i]);
vis[absVal] = true;
} else {
removed.push_back(node[i]);
}
}
if(result.size() != 0) {
for(int i = 0; i < result.size()-1; i++) {
printf("%05d %d %05d\n", result[i].ad, result[i].val, result[i+1].ad);
}
printf("%05d %d -1\n", result.rbegin()->ad, result.rbegin()->val);
}
if(removed.size() != 0) {
for(int i = 0; i < removed.size()-1; i++) {
printf("%05d %d %05d\n", removed[i].ad, removed[i].val, removed[i+1].ad);
}
printf("%05d %d -1\n", removed.rbegin()->ad, removed.rbegin()->val);
}
return 0;
}