func GetListCrossPosition(l1 *List, l2 *List) {
p1 := l1.Front()
p2 := l2.Front()
len1 := 0
len2 := 0
for p1.Next() != nil {
p1 = p1.Next()
len1++
}
for p2.Next() != nil {
p2 = p2.Next()
len2++
}
var p *Element = nil
var shortestPtr *Element = nil
step := 0
if len1 > len2 {
step = len1 - len2
p = l1.Front()
shortestPtr = l2.Front()
} else {
step = len2 - len1
p = l2.Front()
shortestPtr = l1.Front()
}
for i := 0; i < step; i++ {
p = p.Next()
}
var crossNode *Element = nil
for {
if shortestPtr == p {
crossNode = shortestPtr
break
}
p = p.Next()
shortestPtr = shortestPtr.Next()
if p == nil || shortestPtr == nil {
break
}
}
if crossNode != nil {
fmt.Println("l1 l2 相交于", crossNode.Value)
} else {
fmt.Println("l1 l2 不相交")
}
}
评论