Skip to content

Instantly share code, notes, and snippets.

@ljsabc
Created September 20, 2018 13:51
Show Gist options
  • Save ljsabc/785bdfed250ef0062699a14cf03b992c to your computer and use it in GitHub Desktop.
Save ljsabc/785bdfed250ef0062699a14cf03b992c to your computer and use it in GitHub Desktop.
# 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 and headB):
return None
p = headA
q = headB
lenA = 0
lenB = 0
while p.next:
p = p.next
lenA += 1
while q.next:
q = q.next
lenB += 1
if p.val != q.val:
return None
else:
# intersection
p = headA
q = headB
while (lenA > lenB):
p = p.next
lenA -= 1
while (lenB > lenA):
q = q.next
lenB -= 1
while p.val != q.val or p.next != q.next:
p = p.next
q = q.next
return p
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment