《剑指offer》面试题13:两个链表的第一个公共节点

题目描述

输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
 

题目解析:

这道题是什么意思呢?如下图所示:

 

 其中上面的为第一个链表,下面的为第二个链表,它们的公共结点指的就是它们结合之处的那个共同的节点。我们可以先将两个链表的Node分别放到不同的list列表里,然后对这两个列表里的Node进行遍历,发现如果正好有两个Node的数值和指向都是相同的的话就查找成功。因为一个Node想要相同的话,需要具有两个条件,一个条件是:

1.Node当中的数值相同

2.Node当中的指向的是同一个节点

因此代码如下所示:

class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        # write code here
        list_node_one=[]
        list_node_two=[]
        while pHead1:
            list_node_one.append(pHead1)
            pHead1=pHead1.next
            
        while pHead2:
            list_node_two.append(pHead2)
            pHead2=pHead2.next
        #如果是同一个节点,那么这个节点储存的下一个节点的地址以及节点里面的值相同
        for i in list_node_one:
            for j in list_node_two:
                if i.val==j.val and i.next==j.next:
                    return i
        return None

得解!

 

posted @ 2020-08-17 21:12  Geeksongs  阅读(185)  评论(0编辑  收藏  举报

Coded by Geeksongs on Linux

All rights reserved, no one is allowed to pirate or use the document for other purposes.