您的位置:首页 > 其它

PAT ~ L2-002. 链表去重 (思路 + 模拟)

2018-03-13 17:37 232 查看
思路:注意题目数据,地址是一个五位数且不重复!!!所以我们直接可以把他的地址作为结构体数组下标,结构体里面只需要存下个节点的下标(即地址)和键值就行。这样输入以后我们就可以直接遍历这个链表了。开个标记数组来标识键值的绝对值有没有出现过,如果没出现过我们就把地址依次存入一个ans数组,如果出现过就按顺序存入res数组。
输出的时候,两个新链表顺序是按照ans和res来的而不是原来的Next,所以我们按照新的顺序输出就行了。
有个小细节,可能只有第一个链表而没有第二个链表。#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 5;
int S, N;
struct node
{
int Key, Next;
}a[MAXN];
bool vis[MAXN];
int ans[MAXN], res[MAXN];
int main()
{
scanf("%d%d", &S, &N);
for (int i = 0; i < N; i++)
{
int Address;
scanf("%d", &Address);
scanf("%d%d", &a[Address].Key, &a[Address].Next);
}
int cnt1 = 0, cnt2 = 0;
for (int i = S; i != -1; i = a[i].Next)
{
if (!vis[abs(a[i].Key)])
{
ans[cnt1++] = i;
vis[abs(a[i].Key)] = true;
}
else res[cnt2++] = i;
}
printf("%05d %d ", ans[0], a[ans[0]].Key);
for (int i = 1; i < cnt1; i++)
{
printf("%05d\n", ans[i]);
printf("%05d %d ", ans[i], a[ans[i]].Key);
}
printf("-1\n");
if (cnt2)
{
printf("%05d %d ", res[0], a[res[0]].Key);
for (int i = 1; i < cnt2; i++)
{
printf("%05d\n", res[i]);
printf("%05d %d ", res[i], a[res[i]].Key);
}
printf("-1\n");
}
return 0;
}
/*
00100 5
99999 -7 87654
23854 -15 00000
87654 15 -1
00000 -15 99999
00100 21 23854
*/

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: