题目链接
https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
题目描述
代码初步
- 思路:两个单链表的状态有两种,一种不相交,另一种相交。
1.当相交时,我们假设相交点为c,链表A头部到c的距离为m,链表B到c的距离为n,c到两个链表的尾部距离为x。用两个指针依次循环遍历两个链表,如果有一个先遍历完,则让它指向另一个链表的头部再继续遍历,直到两指针相遇。
为什么两个指针会相遇,将c点看成是终点的话,链表A走过的路程是m+x+n,链表B走过的路程是n+x+m,距离相等,所以最后一定会相遇。
2.当不相交时,两指针没有指向同一个地址,return None.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if headA ==None or headB==None:
return None
pa = headA
pb = headB
while(pa!=pb):
if not pa:
pa=headB
else:
pa=pa.next
if not pb:
pb=headA
else:
pb = pb.next
return pa
代码欣赏
-
思路开拓:采用哈希表法
遍历链表 A 并将每个结点的地址/引用存储在哈希表中。然后检查链表 B 中的每一个结点 b是否在哈希表中。若在,则 b为相交结点。 -
复杂度分析
时间复杂度 : O(m+n)。
空间复杂度 : O(m) 或 O(n)。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
pa = headA
pb = headB
hash_table={}
while headA:
hash_table[headA]=1
headA = headA.next
while headB:
if headB in hash_table:
return headB
headB = headB.next
return None