L2-002 链表去重 (25分)
AC代码
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
bool visit[10010];
struct node{
int cur, value, nxt;
}nodes[100010], h[100010], ret1[100010], ret2[100010];
int main(){
int ori, n, pos1 = 0, pos2 = 0, flag = 0;
scanf("%d%d", &ori, &n);
for (int i = 0; i < n; i++){
scanf("%d%d%d", &nodes[i].cur, &nodes[i].value, &nodes[i].nxt);
h[nodes[i].cur] = nodes[i];
}
while (true){
if (!visit[abs(h[ori].value)]){
ret1[pos1++] = h[ori];
visit[abs(h[ori].value)] = true;
}
else {
ret2[pos2++] = h[ori];
flag = 1;
}
if (h[ori].nxt == -1) break;
ori = h[ori].nxt;
}
for (int i = 0; i < pos1-1; i++)
printf("%05d %d %05d\n", ret1[i].cur, ret1[i].value, ret1[i+1].cur);
printf("%05d %d -1\n", ret1[pos1-1].cur, ret1[pos1-1].value);
if (flag){
for (int i = 0; i < pos2-1; i++)
printf("%05d %d %05d\n", ret2[i].cur, ret2[i].value, ret2[i+1].cur);
printf("%05d %d -1\n", ret2[pos2-1].cur, ret2[pos2-1].value);
}
return 0;
}