PAT----A1032 Sharing (25point(s))

A1032 Sharing (25point(s))

题意

给出两条链表并找出共同后缀,输出节点地址,如果没有则输出-1.

思路

建立两条链表倒着遍历。

11111 22222 9
67890 i 00002
00010 a 12345
00003 g -1
12345 D 67890
00002 n 00003
22222 B 23456
11111 L 00001
23456 e 67890
00001 o 00010

Sample Output:

00001 00002 4
00001 a 10001
10001 s -1
00002 a 10002
10002 t -1
#include"bits/stdc++.h"
using namespace std;
const int maxn = 100010;
struct Node{
	int addr;
	int next = -1;
};
Node nodes[maxn];
int main(){
	// freopen("input.txt","r",stdin);
	int head1,head2,n;
	cin >> head1 >> head2 >> n;
	for(int i=0;i<n;i++){
		int addr,next; char e;
		scanf("%d %c %d",&addr,&e,&next);
		nodes[addr].addr = addr;
		nodes[addr].next = next;
	} 
	int t1 = head1;
	list<int> a1;
	while(nodes[t1].next != -1) {
		a1.push_back(t1); t1 = nodes[t1].next;
	}
	int t2 = head2;
	list<int> a2;
	while(nodes[t2].next != -1) {
		a2.push_back(t2); t2 = nodes[t2].next;	
	}
	if(a1.empty() || a2.empty()){
		cout << -1 << endl;
		return 0;
	}
	int ans = -1;
	while(!a1.empty() && !a2.empty() &&a1.back() == a2.back()){
		ans = a1.back();
		a1.pop_back();
		a2.pop_back();
	}
	if(ans == -1)
		printf("-1\n");
	else 
		printf("%05d\n",ans);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值