20201021-相交链表|长短指针

it2024-10-10  41

160.相交链表

# 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 not headA or not headB: return None pA = headA pB = headB while pA != pB: pA = pA.next if pA else headB pB = pB.next if pB else headA return pA 一样都是利用指针最后相遇一开始纠结说如果是两段不相交的链表,就会一直循环,后来发现其实代码的while部分已经限制了,最长只能到len(headA)+len(headB),所以不存在无限循环的问题。另一种解法是暴力解法,比如针对headA的每一个元素去循环一遍headB找相同值。还有就是利用哈希,去找相同值。
最新回复(0)