PAT甲級 1032 Sharing (25分)

分析一下題意,有兩個鏈表,將最早出現的公共節點輸出。
這裏選擇用數組存儲鏈表,下標表示節點,值表示next。
先對第一個鏈表進行遍歷,出現過的進行標記,然後對第二個鏈表遍歷,遇到之前訪問過的則輸出,如果沒有,則輸出“-1”

#include<bits/stdc++.h>
using namespace std;
int node[100010];
int visit[100010];
main()
{
	for(int i=0;i<100000;i++)
	node[i] = -1;
	for(int i=0;i<100000;i++)
	visit[i] = 0;
	int a,b,n;
	scanf("%d %d %d",&a,&b,&n);
	for(int i=0;i<n;i++)
	{
		int address,next;
		char data;
		scanf("%d %c %d",&address,&data,&next);
		node[address] = next;
	}
	int next=a;
	while(next!=-1)
	{
		visit[next] = 1;
		next = node[next];
	}
	next = b;
	while(next!=-1)
	{
		if(visit[next] == 1)
		{
			printf("%05d",next);
			return 0;
		}
		next = node[next];
	}
	printf("-1");
 } 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章