输入两个链表,找出它们的第一个公共结点。
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def FindCommonNode(self, pHead1, pHead2):
nLength1 = self.GetLength(pHead1)
nLength2 = self.GetLength(pHead2)
nDiff = abs(nLength1 - nLength2)
if nLength1 >= nLength2:
nLong = pHead1
nShort = pHead2
else:
nLong = pHead2
nShort = pHead1
for i in range(nDiff):
nLong = nLong.next
while nLong != None and nShort != None and nLong.val != nShort.val:
nLong = nLong.next
nShort = nShort.next
return nLong
def GetLength(self, pHead):
nLength = n
while pHead != None:
pHead = pHead.next
nLength += 1
return nLength
package main
type ListNode struct {
Val int
Next *ListNode
}
func GetCommonNode (l1, l2 *ListNode) *ListNode {
nLength1 := GetLength(l1)
nLength2 := GetLength(l2)
if nLength1 > nLength2 {
nDiff := nLength1 - nLength2
nLong := l1
nShort := l2
} else {
nDiff := nLength2 - nLength1
nLong := l2
nShort := l1
}
for i:=0; i<nDiff; i++ {
nLong = nLong.Next
}
for nLong != nil && nShort != nil && nLong.Val != nShort.Val {
nLong = nLong.Next
nShort = nShort.Next
}
return nLong
}
func GetLength (l1 *ListNode) int {
if l1.Val == nil {
return 0
}
count := 0
for l1 != nil {
l1 = l1.Next
count++
}
return count
}
func firstCommonMap(h1, h2 *LinkNode) *LinkNode {
m := make(map[*LinkNode]bool)
for h1 != nil {
m[h1] = true
h1 = h1.Next
}
for h2 != nil {
if _, ok := m[h2]; ok {
return h2
}
h2 = h2.Next
}
return h2
}
网友评论