题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
公共的部分一定是在这两个链表的后面,不可能存在下面这种情况,这种情况就不叫链表了,两个Next不可能的(当时脑子瓦特了)。
正确的情况就是第二张图。如果只是遍历一个链表的话,公共部分之前的长度是不一样的,所以没办法相遇。但是我们可以遍历两个链表,同时遍历,那么最后一定会相遇。如果没有公共点,那么走到最后,指针都为nil,如果有公共点,一定可以相遇。
- p1指针遍历pHead1链表,遍历完了就去遍历pHead2链表;
- p2指针遍历pHead2链表,遍历完了就去遍历pHead1链表;
- 然后两个指针会相等。都为空则证明没有公共点,不为空就是第一公共点。
package main
import . "nc_tools"
/*
* type ListNode struct{
* Val int
* Next *ListNode
* }
*/
/**
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
func FindFirstCommonNode( pHead1 *ListNode , pHead2 *ListNode ) *ListNode {
// write code here
if pHead1 == nil || pHead2 == nil {
return nil
}
p1, p2 := pHead1, pHead2
// 两个链表公共的部分一定是在后面的一整块
for p1 != p2 {
if p1 == nil {
p1 = pHead2
}else {
p1 = p1.Next
}
if p2 == nil {
p2 = pHead1
}else {
p2 = p2.Next
}
}
if p1 == nil && p2 == nil {
return nil
}
return p1
}

查看3道真题和解析