很简单的一题,两个链表共用尾节点,找出第一个共用节点的地址。
主要思路:先求两个链表的表长,然后将长的一个先行遍历,直至两者相等,然后两表同时遍历,找到公共节点,将其输出。
坑点:因为用int存储的地址,注意输出格式补齐5位
AC代码如下
#include <iostream>
#include <cstring>
using namespace std;
const int max_n = 100010;
struct Node{
char c;
int next;
} node[max_n];
int charlen(int head){
int len = 1;
if(head == -1) return 0;
while(node[head].next != -1){
len++;
head = node[head].next;
}
return len;
}
int main(){
int fh,sh,N;
cin>>fh>>sh>>N;
int add,nadd;
char tem;
for(int i = 0; i < N;i++){
cin>>add>>tem>>nadd;
node[add].c = tem;
node[add].next = nadd;
}
int flen = charlen(fh) , slen = charlen(sh);
//将较长字符串先遍历,直至两者相等
if(flen >= slen){
for(int i = 0; i < flen - slen; i++){
fh = node[fh].next;
}
}
else{
for(int i = 0; i < slen - flen; i++){
sh = node[sh].next;
}
}
//两者同时向后遍历直至找到相同节点
while(fh != sh){
fh = node[fh].next;
sh = node[sh].next;
}
if(fh != -1) {
printf("%05d",fh);
}
else printf("-1");
return 0;
}