PAT-GPLT训练集 L2-002 链表去重

时间:2023-11-23 10:45:20

PAT-GPLT训练集 L2-002 链表去重

题目大意为给出一个单链表,去除重复的结点,输出删除后的链表,并且把被删除的结点也以链表形式输出

思路:把这个链表直接分成两个链表,再直接输出就可以

代码:

#include<iostream>
#include<cstdio>
#include<set>
#include<cmath>
using namespace std;
const int MAX_N = +;
typedef struct { int address, key, next; } P;
P a[MAX_N], b[MAX_N], c[MAX_N]; set<int> check;
int n, s;
int main() {
cin >> s >> n;
int from, key, to;
for(int i = ; i < n; i++) {
scanf("%d%d%d", &from, &key, &to);
a[from].address = from;
a[from].key = key;
a[from].next = to;
}
int c1 = , c2 = ;
while(s != -) {
if(check.count(abs(a[s].key))) {
c[c2++] = a[s];
} else {
check.insert(abs(a[s].key));
b[c1++] = a[s];
}
s = a[s].next;
}
for(int i = ; i < c1; i++) {
if(!i) printf("%05d %d ", b[i].address, b[i].key);
else printf("%05d\n%05d %d ", b[i].address, b[i].address, b[i].key);
}
printf("-1\n");
for(int i = ; i < c2; i++) {
if(!i) printf("%05d %d ", c[i].address, c[i].key);
else printf("%05d\n%05d %d ", c[i].address, c[i].address, c[i].key);
}
if(c2) printf("-1");
return ;
}