Created
December 10, 2018 03:26
-
-
Save jovianlin/272e8ef113bb9df75b5dfc4d77a4a61c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Definition for singly-linked list. | |
# class ListNode(object): | |
# def __init__(self, x): | |
# self.val = x | |
# self.next = None | |
class Solution(object): | |
def getLength(self, node): | |
length = 0 | |
while node: | |
length += 1 | |
node = node.next | |
return length | |
def getIntersectionNode(self, headA, headB): | |
""" | |
:type head1, head1: ListNode | |
:rtype: ListNode | |
""" | |
if headA is None or headB is None: return None | |
if headA.val == headB.val: return headA | |
lengthA, lengthB = self.getLength(headA), self.getLength(headB) | |
if lengthA > lengthB: | |
longerNode, shorterNode = headA, headB | |
else: | |
longerNode, shorterNode = headB, headA | |
difference = int(abs(lengthA - lengthB)) | |
for _ in range(difference): | |
longerNode = longerNode.next | |
while longerNode and shorterNode: | |
if longerNode.val == shorterNode.val: | |
return longerNode | |
else: | |
longerNode = longerNode.next | |
shorterNode = shorterNode.next | |
# End of while loop | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment