PAT A1032(测试点3运行超时)

先看错误代码
提供一组测试用例,即可能存在某一条链表不存在的情况,下述代码没有考虑到,导致程序死循环从而超时(这是链表类问题最容易踩的坑,即忽略链表为空的情况)
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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值