题目: 牛客网链接
概述: 给出两个字符串,用链表来表示(不是严谨的链表,只是表示出每个节点的起始位置,和下一个节点位置)。让找两个字符串的公共节点。
思路: 就是用一个足够大的数组表示可能出现的地址,读取下一个地址,并将对应数组的值+1,当为2的时候就是前缀对应的地址。
当有出现两次的节点一定是公共节点。
我们在采用scanf输入字符的时候要考虑后面的空格或者回车,而采用cin却不会出现这样情况。但是我们为了节约运行时间,采用scanf用法,可以用个字符数组来解决这个问题。
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int nextPosition[100000]; //用来记录下一个位置
int countNum[100000]; //用来记录每个节点被引用的次数,当出现被引用两次的时候,就是公共节点的开始位置。
int main()
{
int firstStart, secondStart, n;
while(scanf("%d%d%d", &firstStart, &secondStart, &n) != EOF)
{
fill(nextPosition, nextPosition+100000, 0);
fill(countNum, countNum+100000, 0);
char temp[2];
int firstPosition, secondPosition;
for(int i = 0; i < n; i++)
{
scanf("%d%s%d", &firstPosition, &temp ,&secondPosition);
nextPosition[firstPosition] = secondPosition;
}
int position = firstStart;
while(position != -1)
{
countNum[position]++;
position = nextPosition[position];
}
int index = -1; //用来记录公共起始位置
position = secondStart;
while(position != -1)
{
countNum[position]++;
if(countNum[position] == 2)
{
index = position;
break;
}
position = nextPosition[position];
}
printf("%d\n", index);
}
return 0;
}
本文介绍了一种使用数组记录节点引用次数的方法,通过两次遍历链表,找到两个链表的第一个公共节点。讨论了使用scanf与cin输入的差异,并提出了解决方案。
4492

被折叠的 条评论
为什么被折叠?



