L[100000]设为removed的头结点。
#include <stdio.h>
#include <math.h>
typedef struct LinkList {
int Key;
int Next;
}LinkList;
int main()
{
LinkList L[100001];
int Add, N, FirstAdd,check[10001],i,Removed;
scanf("%d %d", &FirstAdd, &N);
while (N--) {
scanf("%d", &Add);
scanf("%d %d", &L[Add].Key, &L[Add].Next);
}
for (i = 0; i < 10001; i++)
check[i] = 0;
Add = FirstAdd;
check[abs(L[Add].Key)] = 1;
Removed = 100000;
L[100000].Next = -1;
while (L[Add].Next != -1) {
if (check[abs(L[L[Add].Next].Key)]) {/*删除下一节点*/
L[Removed].Next = L[Add].Next;
L[Add].Next = L[L[Add].Next].Next;
Removed = L[Removed].Next;
}
else {
check[abs(L[L[Add].Next].Key)] = 1;
Add = L[Add].Next;
}
}
for (Add = FirstAdd; Add != -1; Add = L[Add].Next) {
printf("%05d %d ", Add,L[Add].Key);
if (L[Add].Next == -1)
printf("-1\n");
else printf("%05d\n", L[Add].Next);
}
for (Add = L[100000].Next; Add != -1; Add = L[Add].Next) {
printf("%05d %d ", Add, L[Add].Key);
if (L[Add].Next == -1)
printf("-1\n");
else printf("%05d\n", L[Add].Next);
}
return 0;
}