https://pintia.cn/problem-sets/994805342720868352/problems/994805460652113920
思路
用vector建立这2个静态链表,从后往前遍历,遇到不是重复的结点就停
测试点3
遍历的时候不要采取“长的先走,再一起走”这种从前开始遍历的方法,会段错误
#include <iostream>
#include <vector>
using namespace std;
typedef struct {
int adr,next;
char data;
}NODE;
NODE adr[100000];
int main()
{
int head1,head2,n;
vector<NODE> node1,node2;
cin>>head1>>head2>>n;
for (int i=0; i<n; ++i) {
NODE temp;
scanf("%d %c %d",&temp.adr,&temp.data,&temp.next);
adr[temp.adr]=temp;
}
int next=head1;
for (next=head1; next!=-1; next=adr[next].next)
node1.push_back(adr[next]);
for (next=head2; next!=-1; next=adr[next].next)
node2.push_back(adr[next]);
int same=-1;
for (int i=node1.size()-1,j=node2.size()-1; i>=0 && j>=0; --i,--j) {
if (node1[i].adr==node2[j].adr)
same=node1[i].adr;
else
break;
}
if (same!=-1)
printf("%05d",same);
else
printf("-1");
}
这是段错误的遍历方法,不知道是哪儿越界了
int left1=0,left2=0;
if (node1.size()>node2.size()) {
left1=node1.size()-node2.size();
} else
left2=node2.size()-node1.size();
while (node1[left1].adr!=node2[left2].adr && left1<node1.size() && left2<node2.size()) {
++left1;
++left2;
}
if (node1[left1].adr==node2[left2].adr && left2<node2.size() && left1<node1.size())
printf("%05d",node2[left2].adr);
else
cout<<"-1";