Skip to content

Latest commit

 

History

History
87 lines (62 loc) · 2.03 KB

160.md

File metadata and controls

87 lines (62 loc) · 2.03 KB

Intersection of Two Linked Lists

Description

link


Solution

See Code


Code

O(n) & O(1)

# Code 1

class Solution:
    # @param two ListNodes
    # @return the intersected ListNode
    def getIntersectionNode(self, headA, headB):
        if headA is None or headB is None:
            return None

        pa = headA # 2 pointers
        pb = headB

        while pa is not pb:
            # if either pointer hits the end, switch head and continue the second traversal, 
            # if not hit the end, just move on to next
            pa = headB if pa is None else pa.next
            pb = headA if pb is None else pb.next

        return pa # only 2 ways to get out of the loop, they meet or the both hit the end=None

# the idea is if you switch head, the possible difference between length would be countered. 
# On the second traversal, they either hit or miss. 
# if they meet, pa or pb would be the node we are looking for, 
# if they didn't meet, they will hit the end at the same iteration, pa == pb == None, return either one of them is the same,None


# Code 2

# 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
        """
        lena, lenb = 0, 0
        
        pa = headA
        pb = headB
        
        while pa:
            lena += 1
            pa = pa.next
        
        while pb:
            lenb += 1
            pb = pb.next
        
        pa, pb = headA, headB
        
        if lena >= lenb:            
            for _ in range(lena - lenb):
                pa = pa.next
        else:
            for _ in range(lenb - lena):
                pb = pb.next
                
        while pa != pb:
            pa = pa.next
            pb = pb.next
            
        return pa