这个题是个stl模拟链表的题目,按理来说应该是个水题,但写完直接case2段错误,就很尴尬。
先看一下题意思:大致意思是,给定一个链表,你需要给链表去重,重复标准是:abs(key)
已经出现过,把后出现的重复节点删掉,但是输出时要先输出去重后的链,之后输出删除的节点连成的链。
输入:首个节点的地址 节点数n 下面n行是节点的信息
输出:两条链
题意很清楚,就是根据key值做重复的删减。可以用个结构体存节点信息,先把随机输入的节点连成一条链,然后再做删减。在判定重复时,可以将abs(key)
插入到set中,枚举过程中,每次检验set中是否已经存在该值,存在就删除,也就是保存到一个vector中,不存在就插入进去,并且将该节点保存到需要第一个输出的数组中。
思路也很简单,但是case2直接段错误了。。。
很尴尬,我开始以为是数组开小了,开到1e8+10,一样段错误,参考别的大佬的代码找到了原因:是stl引起的,参考博客,有可能存在某个串为空
的情况,需要输出时加一个判断就好了。
源码:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <set>
using namespace std;
const int maxn = 1e6+10, inf = 0x3f3f3f3f;
struct Node {
int address, key, next;
};
Node v[maxn];
vector <Node> node, res;
set <int> s;
int n, _first;
int main() {
cin >> _first >> n;
for (int i = 0; i < n; i++) {
int a, b, c;
cin >> a >> b >> c;
Node nn;
nn.address = a, nn.key = b, nn.next = c;
v[a] = nn;
}
for (; _first != -1; _first = v[_first].next) {
if (s.find(abs(v[_first].key)) == s.end()) {
s.insert(abs(v[_first].key));
res.push_back(v[_first]);
} else {
node.push_back(v[_first]);
}
}
if (res.size() > 0) {
for (int i = 0; i < res.size()-1; i++)
printf("%05d %d %05d\n", res[i].address, res[i].key, res[i+1].address);
printf("%05d %d -1\n", res[res.size()-1].address, res[res.size()-1].key);
}
if (node.size() > 0) {
for (int i = 0; i < node.size()-1; i++)
printf("%05d %d %05d\n", node[i].address, node[i].key, node[i+1].address);
printf("%05d %d -1\n", node[node.size()-1].address, node[node.size()-1].key);
}
return 0;
}
编码不规范,debug泪两行…⊛_⊛
欢迎大佬们指正