两个链表的第一个公共节点-python

思路:因为当出现一个公共节点时,后面的节点都相同(因为链表的后继节点是唯一的,也就表明公共节点的后继一定相同,以此类推,后面的节点都相等),因此可以将所有节点放入栈中,从后往前看,直到不相同的点,那么他的前一个节点就是第一个公共节点了。

# -*- 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
        stack1 = []
        stack2 = []
        p1 = pHead1
        p2 = pHead2
        while p1:
            stack1.append(p1)
            p1 = p1.next
        while p2:
            stack2.append(p2)
            p2 = p2.next
        pre = None
        while stack1 and stack2 and stack1[-1] == stack2[-1]:
            pre = stack1.pop()
            stack2.pop()
        return pre
posted @ 2019-08-05 19:56  Dolisun  阅读(604)  评论(0编辑  收藏  举报