# coding=utf-8 class ListNode(): def __init__(self, x): # 定义链表节点 self.val = x self.next = None def findcommon(p1, p2): n1 = Getlength(p1) n2 = Getlength(p2) n3 = abs(n1 - n2) if n1 > n2: pL = p1 ps = p2 pass else: pL = p2 ps = p1 pass for i in range(n3): pL = pL.next pass while pL != None and ps != None and pL.val != ps.val: pL = pL.next ps = ps.next pass if pL is None: return None else: return pL.val pass def Getlength(p): n = 0 while p != None: p = p.next n += 1 return n def genList(data):#构建链表 if len(data) == 0: return None head = ListNode(data[0]) tmp = head for item in data[1:]: tmp.next = ListNode(item) tmp = tmp.next pass return head pass if __name__ == '__main__': p1 = [1, 2, 3, 6, 7] p2 = [4, 5, 6, 7] s1 = genList(p1) s2 = genList(p2) print findcommon(s1, s2)
offer37--两个链表的公共节点
最新推荐文章于 2022-10-31 15:39:53 发布