两个链表的第一个公共结点
时间限制:1秒 空间限制:32768K 热度指数:192897
本题知识点: 链表
算法知识视频讲解
题目描述
输入两个链表,找出它们的第一个公共结点。
法1.
两条相交的链表呈Y型。可以从两条链表尾部同时出发,最后一个相同的结点就是链表的第一个相同的结点。可以利用栈来实现。时间复杂度有O(m + n), 空间复杂度为O(m + n)
代码
链接:https://www.nowcoder.com/questionTerminal/6ab1d9a29e88450685099d45c9e31e46
来源:牛客网
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
if not pHead1 or not pHead2:
return None
stack1 = []
stack2 = []
while pHead1:
stack1.append(pHead1)
pHead1 = pHead1.next
while pHead2:
stack2.append(pHead2)
pHead2 = pHead2.next
first = None
while stack1 and stack2:
top1 = stack1.pop()
top2 = stack2.pop()
if top1 is top2:
first = top1
else:
break
return first
法2.
思路一其实利用栈主要解决就是同时到达第一个结点的问题。那么从链表头出发如何同时到达第一个相同的结点呢? 链表的长度相同就可以,其实就是走的结点数目相同。所以可以让其中长的链表先走几步,剩余的长度到短链表的长度相同。
# -*- 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 or not pHead2:
return None
p1, p2 = pHead1, pHead2
length1 = length2 = 0
while p1:
length1 += 1
p1 = p1.next
while p2:
length2 += 1
p2 = p2.next
if length1 > length2:
while length1 - length2:
pHead1 = pHead1.next
length1 -= 1
else:
while length2 - length1:
pHead2 = pHead2.next
length2 -= 1
while pHead1 and pHead2:
if pHead1 is pHead2:
return pHead1
pHead1 = pHead1.next
pHead2 = pHead2.next
return None
链接:https://www.nowcoder.com/questionTerminal/6ab1d9a29e88450685099d45c9e31e46
来源:牛客网