代码
#include <iostream>
using namespace std;
#define MaxSize 100000
typedef struct node{
//int address;
char data;
int next_address;
int flag;
}Node;
int main(){
Node linklist[MaxSize];
int head1,head2,num;
cin>>head1>>head2>>num;
cout<<num<<endl;
while(num--){
int address;//提供数组下标
char data;
int next_address;
cin>>address>>data>>next_address;
linklist[address].data = data;
linklist[address].next_address = next_address;
linklist[address].flag=0;
}
int p = head1;
while(linklist[p].next_address!=-1){
linklist[p].flag=1;
p = linklist[p].next_address;
}
p = head2;
while(linklist[p].next_address!=-1){
if(linklist[p].flag==1) {
cout<<p<<endl;
break;
}
else{
p = linklist[p].next_address;
}
}
cout<<"-1"<<endl;
return 0;
}
思路
使用静态链表,多一个flag域指示当前结点属于哪个链表,然后遍历第一个链表将flag置1,最后遍历第二个链表如果第二个链表遍历到的结点出现flag==1的即证明二者有相同结点。没有输出-1
模版
//定义静态链表
struct Node{
int address;//结点地址
typename data;//数据
int next;
xxx;//结点的某个性质,不同的题目会有不同的设置
}node[100010];
//在程序的开始对静态链表进行初始化
for(int i=0;i<maxn;i++){
node[i].xxx = 一个无法到达的value;
}
//题目一般会给出首结点地址,然后可以根据这个地址来遍历整条链表
//同时对结点的性质xxx进行标记
//对有效结点进行计数
int p = begin,count = 0;
while(p != -1){
xxx = 1;//对性质进行标记
count++;//计数当前有效结点
p = node[p]->next;
}
//使用静态链表时,采用hash的方式,所以会导致地址不连续
//这个时候整个数组中可能存有有效值,也可能有无效值,这个时候就需要将所有有效值移到数组的左侧,无效值往后
//这个时候利用到了标志信息xxx和有效结点计数值count,移动之后可以使用count访问全部有效值
//一般来说,题目会有额外要求,所以还需要二级排序
bool cmp(Node a,Node b){
if(a.xxx==-1||b.xxx=-1){
//至少有一个是无效结点,将其放在数组后边
return a.xxx>b.xxx;
}
else{
//二级排序
}
}