一、题目
输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
二、分析及代码
1. 同步位置
(1)思路
在公共结点后,两个链表的后续结点是完全相同的,因此可对两个链表从后往前的对应位置同步后依次比对得到第一个公共结点。
通过对两个链表分别进行一次遍历,获得各自的长度,计算长度差后,由较长的链表先跳过相应结点个数,然后同时依次遍历,比较对应结点是否相同。
(2)代码
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if (pHead1 == null || pHead2 == null)
return null;
int len1 = 0, len2 = 0;
ListNode cHead1 = pHead1;
ListNode cHead2 = pHead2;
while (cHead1 != null) {
cHead1 = cHead1.next;
len1++;
}
while (cHead2 != null) {
cHead2 = cHead2.next;
len2++;
}
if (len1 >= len2) {
cHead1 = pHead1;
cHead2 = pHead2;
}
else {
cHead1 = pHead2;
cHead2 = pHead1;
}
for (int i = len1 - len2; i > 0; i--)
cHead1 = cHead1.next;
while (cHead1 != null && cHead2 != null && cHead1 != cHead2) {
cHead1 = cHead1.next;
cHead2 = cHead2.next;
}
return cHead1;
}
}
(3)结果
运行时间:17ms,占用内存:9660k。
三、其他
暂无。