PAT甲题题解-1032. Sharing (25)-链表水题
#include <iostream> #include <cstdio> #include <algorithm> #include <string.h> #include <cmath> using namespace std; /* 链表题 水 */ int n; struct Word{ int addr; char ch; int next=-1; }word[100000]; int vis[100000]; int main() { int first1,first2; int adr,nxt; char ch; scanf("%d %d %d",&first1,&first2,&n); for(int i=0;i<n;i++){ scanf("%d %c %d",&adr,&ch,&nxt); word[adr].addr=adr; word[adr].ch=ch; word[adr].next=nxt; } memset(vis,0,sizeof(vis)); while(first1!=-1){ vis[first1]=1; first1=word[first1].next; } bool flag=false; while(first2!=-1){ if(vis[first2]){ flag=true; break; } first2=word[first2].next; } if(flag) printf("%05d\n",first2); else printf("-1\n"); return 0; }