题目:
解题思路:
- 两个链表有长有短,先把长短确定下来
- 短的链表不动,长的链表往后面移,移它们的长度差
- 为什么要长的往后移呢? - 两个链表的的公共节点,顶天把短的整个作为公共链了,所以长链往后移
- 由于返回值需要的是一个链表,所以开辟一个新链,找到一个公共部分后链接上就行了
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# @param pHead1 ListNode类
# @param pHead2 ListNode类
# @return ListNode类
#
class Solution:
def FindFirstCommonNode(self , pHead1 , pHead2 ):
# write code here
if not pHead1 or not pHead2:
return None
res = ListNode(0)
r = res
p = pHead1
q = pHead2
count1 = 0
count2 = 0
while p:
p = p.next
count1 += 1
while q:
q = q.next
count2 += 1
p, q = pHead1, pHead2
if count1 > count2: # # pHead1 > pHead2
for i in range(count1-count2):
p = p.next
else:
for i in range(count2-count1):
q = q.next
while p and q:
if p.val == q.val:
r.next = p
r = r.next
p = p.next
q = q.next
return res.next
|