Leetcode 160. Intersection of Two Linked Lists
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
begin to intersect at node c1.
思路是找到长链表从哪个位置与短链表可以同步,因为后面的长度都是一样的,假设它们一样长的话总是会相遇的,所以只要找到哪个最长,同时从相同的地方往后走就好,代码如下:
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if(headA==None or headB==None ):
return None
lenA = self.countLength(headA)
lenB = self.countLength(headB)
gap = 0
if(lenA > lenB):
large, small = headA, headB
gap = lenA - lenB
else:
large, small = headB, headA
gap = lenB - lenA
while(gap > 0):
large = large.next
gap -= 1
while(large!=None and small!= None):
if(large == small):
return small
else:
large = large.next
small = small.next
def countLength(self, head):
count = 0
while head != None:
head = head.next
count += 1
return count
这个算法最坏的情况时间复杂度是O(a+b+b) b>a,a,b为两个链表长短,但其实还是O(n)的。