【leetcode】160: 相交链表

题目如下:

 

这个题目,一看可以把链表的nods全部拿到,放到set哈希表里面,也可以放在list里面,然后循环判断是否有两个地址相同的node,但是由于时间的限制只能在o(n)以内,因此我们可以采用哈希表,也就是python里面的set来做这道题,解答如下:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        if headB == None or headA==None:
            return None
        ls_one=set()
        while headA:
            ls_one.add(headA)
            headA=headA.next
        while headB:
            if headB in ls_one:
                return headB
            headB=headB.next
        

        return None

方法二:

提前遍历两个linked list,得到两个linked list分别的长度,然后将长的linked list前面先走过,直到两个linked list长度一样的时候,开始一一比对当前的node是否一致。这个方法实现起来也比较简单,这里就不提供代码啦!思路就可以啦

posted @ 2021-08-29 20:37  Geeksongs  阅读(32)  评论(0编辑  收藏  举报

Coded by Geeksongs on Linux

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