题目描述 输入两个链表,找出它们的第一个公共结点。
先建立辅助链表,测出2个链表的长度,从长链表数2个链表长度差的步数,再让2个链表一起走
如1, 2, 3, 4, 5和6 ,4, 5 4,5是2个链表相交的部分
两条相交的链表呈Y型,尾部相同 用is
返回第一个公共节点 ,后面的不返回
# -- coding:utf-8 --
class ListNode:
def init(self, x):
self.val = x
self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
if not pHead1 or not pHead2:
return None
p1, p2 = pHead1, pHead2
length1 = length2 = 0
while p1:
length1 += 1
p1 = p1.next
while p2:
length2 += 1
p2 = p2.next
if length1 > length2:
while length1 - length2:
pHead1 = pHead1.next
length1 -= 1
else:
while length2 - length1:
pHead2 = pHead2.next
length2 -= 1
while pHead1 and pHead2:
if pHead1 is pHead2:
return pHead1
pHead1 = pHead1.next
pHead2 = pHead2.next
return None
if __name__ == "__main__":
node11 = ListNode(1) #调用ListNode()类
node12 = ListNode(2)
node13 = ListNode(3)
node14 = ListNode(4)
node15 = ListNode(5)
node21 = ListNode(6)
node11.next = node12
node12.next = node13
node13.next = node14
node14.next = node15
node21.next = node14
s = Solution()
print(s.FindFirstCommonNode(node11, node21))