PAT A1032 Sharing (25分)



将所有的节点存在node数组中,并且将flag设置为false,在遍历第一个链表时,将此链表的节点的flag设置为true,在遍历第二个链表时查询节点的flag值,若发现flag为true,这此节点即为要找的共同后缀的起点,在遍历第一个链表的时候,已经将node中属于第一个链表的节点标记出来,当第二个节点访问到true节点的时,表明访问到了既属于第一个链表的节点有属于第二个链表的节点,很容易理解,两个链表的初次交汇点即为共同后缀的起点。

注意:题目要求的地址是位数,在最终输出的时候可能位数不齐,则要用0补齐,这个容易疏忽*

#include<cstdio>
using namespace std;
const int N = 100010;
struct Node{
    char letter;
    int next;
}node[N];
bool isvis[N];
int main(){
    int w1,w2,n;
    scanf("%d %d %d",&w1,&w2,&n);
    int tempadd,tempnext;
    char templetter;
    bool flag = false;
    int common;
    for(int i = 0;i<n;i++){
        scanf("%d %c %d",&tempadd,&templetter,&tempnext);
        node[tempadd].letter = templetter;
        node[tempadd].next = tempnext;
    }
    while(w1!=-1){
        isvis[w1] = true;
        w1 = node[w1].next;
    }
    while(w2!=-1){
        if(isvis[w2]==true){
            common = w2;
            flag = true;
            break;
        }else{
            isvis[w2] = true;
            w2 = node[w2].next;
        }
    }
    if(flag==true) printf("%05d",common);
    else printf("-1");
    
    return 0;
}
原文地址:https://www.cnblogs.com/shuibeng/p/13595280.html