52. 两个链表的第一个公共节点(简单)

题目描述:找出如下两个链表的第一个公共节点:

思路:从两个链表的后面开始对比,直到找到最后一个链表的节点:

# 方法2. 从尾部开始
        stack1=[]
        stack2=[]
        while headA:
            stack1.append(headA)
            headA=headA.next
        while headB:
            stack2.append(headB)
            headB=headB.next
        same_node=None
        while stack2 and stack1:
            node1=stack1.pop()
            node2=stack2.pop()
            if node1 is node2:
                same_node=node1
            else:
                break
        return same_node

猜你喜欢

转载自blog.csdn.net/weixin_38664232/article/details/104993037