一、题目描述
Input Specification:
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
二、解题思路
链表题,同样地,我们这里可以用静态链表来存储数据,用bool数组flag标记某个数是否已经出现过,用list和removed两个vector<int>存放有效数据和需要移除的数据,按照链表特性从起点进行遍历即可。详情可看代码注释。
三、AC代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 100010;
bool flag[10001] = {false};
vector<int> list, removed; //记录应该被输出的,和移除的
struct Node
{
int data, next;
}node[maxn];
int main()
{
int N, first, tmp;
scanf("%d%d", &first, &N);
for(int i=0; i<N; i++)
{
scanf("%d", &tmp);
scanf("%d%d", &node[tmp].data, &node[tmp].next);
}
tmp = first;
int tmpkey;
while(tmp != -1)
{
tmpkey = abs(node[tmp].data); //tmpkey存放数据的绝对值
if(flag[tmpkey]) //如果已经出现过绝对值相同的数
removed.push_back(tmp); //移除
else
{
flag[tmpkey] = true; //将flag设置为true
list.push_back(tmp); //放入list
}
tmp = node[tmp].next; //转到下一个结点
}
int sze1 = list.size(), sze2 = removed.size();
for(int i=0; i<sze1-1; i++)
{
printf("%05d %d %05d\n", list[i], node[list[i]].data, list[i+1]);
}
printf("%05d %d -1\n", list[sze1-1], node[list[sze1-1]].data);
if(sze2 > 0)
{
for(int i=0; i<sze2-1; i++)
{
printf("%05d %d %05d\n", removed[i], node[removed[i]].data, removed[i+1]);
}
printf("%05d %d -1", removed[sze2-1], node[removed[sze2-1]].data);
}
return 0;
}