题目描述
输入两个链表,找出它们的第一个公共结点。
思路一:两条相交的链表呈Y型。可以从两条链表尾部同时出发,最后一个相同的结点就是链表的第一个相同的结点。可以利用栈来实现。时间复杂度有O(m + n), 空间复杂度为O(m + n)
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
if not pHead1 and not pHead2:
return None
li1 = []
li2 = []
while pHead1:
li1.append(pHead1)
pHead1 = pHead1.next
while pHead2:
li2.append(pHead2)
pHead2 = pHead2.next
first = None
while li1 and li2:
top1 = li1.pop()
top2 = li2.pop()
if top1 is top2:
first = top1
else:
break
return first
思路二:思路一其实利用栈主要解决就是同时到达第一个结点的问题。那么从链表头出发如何同时到达第一个相同的结点呢? 链表的长度相同就可以,其实就是走的结点数目相同。所以可以让其中长的链表先走几步,剩余的长度到短链表的长度相同。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
if not pHead1 and not pHead2:
return None
ln1 = ln2 = 0
p1, p2 = pHead1, pHead2
# 判断两个链表的长度
while pHead1:
ln1 += 1
pHead1 = pHead1.next
while pHead2:
ln2 += 1
pHead2 = pHead2.next
# 把长的链表往后移动,直到两个链表长度相同为止
if ln1 > ln2:
while ln1 - ln2:
p1 = p1.next
ln1 -= 1
else:
while ln2 - ln2:
p2 = p2.next
ln2 -= 1
while p1 and p2:
if p1 == p2:
return p1
p1 = p1.next
p2 = p2.next
return None