[剑指Offer 37] 两个链表的第一个公共节点(Python)
2017-08-18 19:29
513 查看
题目描述
输入两个链表,找出它们的第一个公共结点。思路
思路一两个有公共节点的链表是Y字型的结构,自公共节点后是重合的。可以借助两个栈先存储链表的节点。然后两个栈每次出栈一个节点,如果是重合节点,那么这两个节点是相等的。所以最后一个相等的节点就是第一个公共节点。
思路二
先遍历两个链表,统计长度a和b。让长链表先走|a−b|步,公共节点肯定是存在于后面部分中。然后再对两个链表遍历匹配,遇到的第一个相同节点就是公共节点。
代码
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 思路一 def FindFirstCommonNode1(self, pHead1, pHead2): # write code here if pHead1 is None or pHead2 is None: return None s1 = [] s2 = [] p1 = pHead1 p2 = pHead2 while p1 is not None: s1.append(p1) p1 = p1.next while p2 is not None: s2.append(p2) p2 = p2.next res = None while len(s1) > 0 and len(s2) > 0: v1 = s1.pop() v2 = s2.pop() if v1 == v2: res = v1 else: break return res # 思路二 def getIntersectionNode2(self, headA, headB): # write your code here s1 = 0 s2 = 0 h1 = headA h2 = headB while h1 is not None: s1 += 1 h1 = h1.next while h2 is not None: s2 += 1 h2 = h2.next if s2 > s1: h2 = headB while s2 - s1 > 0: h2 = h2.next s2 -= 1 h1 = headA elif s2 < s1: h1 = headA while s1 - s2 > 0: h1 = h1.next s1 -= 1 h2 = headB else: h1 = headA h2 = headB res = None while h1 is not None and h2 is not None: if h1 == h2: res = h1 return h1 h1 = h1.next h2 = h2.next return res
复杂度分析
思路一:时间复杂度O(m+n),空间复杂度O(m+n)。思路二:时间复杂度O(m+n),空间复杂度O(1)。
相关文章推荐
- 找到两个链表的第一个公共节点 37--剑指offer
- 剑指offer 37 - 两个链表的第一个公共节点
- 【面试题】剑指Offer-37-求两个链表的第一个公共节点
- 剑指offer 37:求两个链表的第一个公共节点
- [剑指offer][面试题37]两个链表的第一个公共节点
- 剑指Offer 37题 两个链表的第一个公共节点 Java版
- 【剑指offer】面试题37:两个链表的第一个公共结点
- 剑指Offer学习总结-两个链表的第一个公共节点
- 剑指offer 面试题37 两个链表的第一个公共结点
- 【剑指Offer学习】【面试题37:两个链表的第一个公共结点】
- 剑指Offer面试题37(Java版):两个链表的第一个公共结点
- 剑指offer-面试题37-两个链表的第一个公共结点
- 剑指offer-37 两个链表的第一个公共结点
- 剑指offer——面试题37:两个链表的第一个公共结点
- 剑指offer--两个链表的第一个公共节点
- 剑指Offer---面试题37:两单链表中第一个公共节点
- 【剑指offer】面试题37:两个链表的第一个公共结点
- 剑指offer 37---求两个链表的第一个公共结点
- 剑指offer 面试题37 两个链表的第一个公共结点
- 剑指offer--面试题37:两个链表的第一个公共结点