输入两个链表,找出它们的第一个公共结点。
思路:
1.先遍历两个链表,计算出长度
2.让长度较长的先走 先走步数=长度差
3.然后再两个链表一起走,值相同的第一个就是两个链表第一个公共节点
时间复杂度:o(m+n)
空间复杂度:比实现两个栈的思想低。
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
nlength1 = self.LengthListNode(pHead1)
nlength2 = self.LengthListNode(pHead2)
nLengthDiff = abs(nlength1-nlength2)
if nlength1<nlength2:
pListHeadShort = pHead1
pListHeadLong = pHead2
else:
# 把相等的情况一定也要算进去
pListHeadShort = pHead2
pListHeadLong = pHead1
for i in range(nLengthDiff):
pListHeadLong = pListHeadLong.next
while pListHeadLong and pListHeadShort and pListHeadLong!=pListHeadShort:
pListHeadLong = pListHeadLong.next
pListHeadShort = pListHeadShort.next
FirstCommond = pListHeadShort
return FirstCommond
def LengthListNode(self,pHead):
if pHead == None:
return 0
else:
length = 0
while pHead:
pHead = pHead.next
length+= 1
return length
if __name__ == '__main__':
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node1.next = node2
node2.next = node3
node4 = ListNode(4)
node5 = ListNode(5)
node4.next = node5
node6 = ListNode(6)
node7 = ListNode(7)
node5.next = node6
node6.next = node7
node3.next = node7
s = Solution()
print(s.FindFirstCommonNode(node1,node4).val)