一、题目描述
输入两个链表,找出它们的第一个公共结点。
二、解题思路
把两个链表拼接起来,一个pHead1在前pHead2在后,一个pHead2在前pHead1在后。生成两个相同长度的链表,同时遍历这两个链表,就能找到公共结点。(PS:公共结点之后的结点均相同)
例如:
链表1:a -> b -> c -> d
链表2:e -> f -> g -> c -> d
拼接两个链表:新链表1=链表1 -> 链表2;新链表2=链表2 -> 链表1
新链表1:a -> b -> c -> d -> e -> f -> g -> c -> d
新链表2:e -> f -> g -> c -> d -> a -> b -> c -> d
同时遍历,即能找到公共结点
如果两者没有公共结点,同时遍历到新链表尾null,即返回null
三、编程实现
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode p1 = pHead1;
ListNode p2 = pHead2;
while (p1 != p2) {
// 当遍历完链表1则接上链表2
p1 = (p1 == null ? pHead2 : p1.next);
// 当遍历完链表2则接上链表1
p2 = (p2 == null ? pHead1 : p2.next);
}
return p1;
}
}