PAT Advanced 1032 Sharing (25 )

题目描述

在这里插入图片描述

Input Specification:

在这里插入图片描述

Output Specification:

在这里插入图片描述

Sample Input:

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:

67890

解题思路

求两个链表的公共结点,先获取两个链表的长度,然后用快慢指针,快指针比慢指针多走abs(L1-L2)的距离

Code

  • AC代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+10;
int node[maxn];

int getLinkListLength(int head) {
	int length = 0;
	while(head != -1) {
		length++;
		head = node[head];
	}
	return length;
}
int main() {
	//freopen("in.txt", "r", stdin);
	int head1, head2, N;
	cin >> head1 >> head2 >> N;
	int address;
	string val;
	for(int i = 0; i<N; i++) {
		cin >> address >> val;
		cin >> node[address];
	}
	int length1 = getLinkListLength(head1);
	int length2 = getLinkListLength(head2);
	if(length1 > length2) {
		for(int i = 0; i<length1-length2; i++) {
			head1 = node[head1];
		} 
	} else {
		for(int i = 0; i<length2-length1; i++) {
			head2 = node[head2];
		}
	}
	while(head1 != -1 && head1 != head2) {
		head1 = node[head1];
		head2 = node[head2];
	}
	if(head1 == -1) {
		printf("-1\n");
	} else {
		printf("%05d\n", head1);
	}
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值