【机试练习】【C++】【PAT A1032】Sharing

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Xiblade/article/details/82939651

此题考静态链表的知识点,注意在链表的数据域中加入一个是否遍历过的bool位

#include<cstdio>

using namespace std;
// 应用静态链表
struct Node{
	char data;
	int next;
	bool isFirst;
	Node(){
		data = ' ';
		next = -1;
		isFirst = false; 
	}
} node[100010]; 

int main(){
	int h1, h2, N;
	scanf("%d %d %d", &h1, &h2, &N);
	// 扫描并构造静态链表 
	int tmpAddress, tmpNext;
	char tmpData;
	for(int i = 0; i < N; i++){
		 scanf("%d %c %d", &tmpAddress, &tmpData, &tmpNext);
		 node[tmpAddress].data = tmpData;
		 node[tmpAddress].next = tmpNext;
	}
	// 遍历第一条路径 将记录置为true 
	int p = h1;
	while(p != -1){
		node[p].isFirst = true;
		p = node[p].next;
	} 
	// 遍历第二条路路径 关注记录的值 
	p = h2;
	while(!node[p].isFirst && p != -1){
		p = node[p].next;
	}
	
	//printf("%d", p); // 这样会有一个测试用例错误
	if(p != -1){
		printf("%05d", p);// 地址要格式化输出 
	} else{
		printf("%d", p);
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Xiblade/article/details/82939651
今日推荐