PAT Advanced 1032 Sharing (25 )
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;
}