题目描述
输入两个链表,找出它们的第一个公共结点。
思路一:两个链表如果有公共结点的话那么他们整体肯定是呈Y字形,那我可以先让长的链表往前走几步,直到它后面的长度和短的链表一样长的时候再让两者一起走,到达的第一个公共结点就是所求啦~
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
pNode1 = pHead1 #这样是为了不改变pHead1和pHead2的指向
pNode2 = pHead2
n1 = n2 = 0
if not pNode1 and not pNode2: #只要有一个为空就返回空
return None
while pNode1: #统计两个链表的长度
n1 += 1
pNode1 = pNode1.next
while pNode2:
n2 += 1
pNode2 = pNode2.next
p1 = pHead1
p2 = pHead2
if n1 >= n2 : #让长的先走几步
for i in range(n1-n2):
p1 = p1.next
else:
for i in range(n2 - n1):
p2 = p2.next
while p1 and p2: #长的走完之后两者一起走,这里判断时可以只判断p1或者p2
if p1 == p2:
return p1
p1 = p1.next
p2 = p2.next
return None
思路二:我们知道两个肯定是呈一个Y字关系,那么我们要是从最后一个结点向前遍历的话,那么到达的最后一个公共结点就是我们要找的第一个结点。后进先出可以用栈的思想。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
pNode1 = pHead1
pNode2 = pHead2
if not pNode1 and not pNode2:
return None
li1 = []
li2 = []
while pNode1:
li1.append(pNode1) #append的是整个结点
pNode1 = pNode1.next
while pNode2:
li2.append(pNode2)
pNode2 = pNode2.next
first = None
while li1 and li2: #这里注意要判断两个,因为有可能两个没公共结点,又不一样长,那就有可能出现一个pop没了的情况,但是又没判断两者长短,所以判断条件两者都要放上
p1 = li1.pop()
p2 = li2.pop()
if p1 == p2:
first = p1
else:
break
return first