先看错误代码
提供一组测试用例,即可能存在某一条链表不存在的情况,下述代码没有考虑到,导致程序死循环从而超时(这是链表类问题最容易踩的坑,即忽略链表为空的情况)
00001 -1 2
00001 a 10001
10001 s -1
#include<iostream>
using namespace std;
const int maxn = 1000010;
struct Node{
int next;
char data;
bool flag;
Node() {
flag = false;
}
}node[maxn];
int main() {
int first1, first2, n, address;
scanf("%d%d%d", &first1, &first2, &n);
for(int i = 0; i < n; i++) {
scanf("%d ", &address);
scanf("%c %d", &node[address].data, &node[address].next);
}
node[first1].flag = true;
for(; node[first1].next != -1; first1 = node[first1].next) {
node[first1].flag = true;
}
for(; node[first2].next != -1 && node[first2].flag == false; first2 = node[first2].next) {
}
if(node[first2].next != -1) printf("%05d", first2);
else printf("-1");
return 0;
}
AC代码(仔细对比区别)
#include<cstdio>
using namespace std;
const int maxn = 100010;
struct Node{
int next;
char data;
bool flag;
Node() {
flag = false;
}
}node[maxn];
int main() {
int first1, first2, n, address, next;
char data;
scanf("%d%d%d", &first1, &first2, &n);
for(int i = 0; i < n; i++) {
scanf("%d %c %d", &address, &data, &next);
node[address].data = data;
node[address].next = next;
}
for(; first1 != -1; first1 = node[first1].next) {
node[first1].flag = true;
}
for(; first2 != -1 && node[first2].flag == false; first2 = node[first2].next) {
}
if(node[first2].flag) printf("%05d", first2);
else printf("-1");
return 0;
}