python3版优质解答

两个链表的第一个公共结点

http://www.nowcoder.com/questionTerminal/6ab1d9a29e88450685099d45c9e31e46

思路:如果两个列表长度相等,则可以使用双指针遍历两个链表。
知识点:1+2=2+1
链表1:1--2--3--4--8--5--1 游标a
链表2:2--4--8--5--1 游标b
a轮询路径 链表1的 1--2--3--4--8--5--1--链表2的2--4--8
b轮询路径 链表2的 2--4--8--5--1--链表1的1--2--3--4--8
发现只要分别同时轮询1+2和2+1,总是能找到公共节点并返回;如果没有公共点,则两个游标最终指向None,退出循环并返回。

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

#
# 
# @param pHead1 ListNode类 
# @param pHead2 ListNode类 
# @return ListNode类
#
class Solution:
    def FindFirstCommonNode(self , pHead1 , pHead2 ):
        cur1=pHead1
        cur2=pHead2

        while (cur1!=cur2):
            cur1=cur1.next if cur1 else pHead2
            cur2=cur2.next if cur2 else pHead1

        return cur1







全部评论

相关推荐

头像
不愿透露姓名的神秘牛友
04-02 20:12
点赞 评论 收藏
转发
投递美团等公司9个岗位
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务