52. The first common node of two linked lists (simple)

Title description: Find the first common node of the following two linked lists:

Idea: Start the comparison from the back of the two linked lists until you find the node of the last linked list:

# 方法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

 

Guess you like

Origin blog.csdn.net/weixin_38664232/article/details/104993037