36.两个链表的第一个公共结点
题目描述
输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
记录
公共节点:单链表,该节点及其之后的节点都相同。
方法一:
指针。
- 有公共节点
- 无公共节点
同时为空,不会陷入死循环。
# -*- 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
p1 = pHead1
p2 = pHead2
while p1 != p2:
if p1 == None:
p1 = pHead2
else:
p1 = p1.next
if p2 == None:
p2 = pHead1
else:
p2 = p2.next
return p2
备注:先遍历两个链表,统计长度。让长链表先走相差的步,然后再对两个链表进行遍历匹配,遇到的第一个相同节点就是公共节点。
方法二:
栈
最后一个相等的节点就是第一个公共节点。
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
stack1 = []
stack2 = []
while pHead1:
stack1.append(pHead1)
pHead1 = pHead1.next
while pHead2:
stack2.append(pHead2)
pHead2 = pHead2.next
res = None
while stack1 and stack2:
p1 = stack1.pop()
p2 = stack2.pop()
if p1 == p2:
res = p1
else:
break
return res
方法三:
set()
讨论中看见的。
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
res = set()
while pHead1:
res.add(pHead1)
pHead1 = pHead1.next
while pHead2:
if pHead2 in res:
return pHead2
pHead2 = pHead2.next
tips
有环或无环?
参考