-
Notifications
You must be signed in to change notification settings - Fork 0
/
160. Intersection of Two Linked Lists
44 lines (40 loc) · 1.12 KB
/
160. Intersection of Two Linked Lists
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# 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 headA == None or headB == None:
return None
def listLen(head):
if head == None:
return 0
length = 1
while head.next != None:
length += 1
head = head.next
return length
lenA = listLen(headA)
lenB = listLen(headB)
if lenA > lenB:
diff = lenA-lenB
for i in range(diff):
headA = headA.next
elif lenB > lenA:
diff = lenB-lenA
for i in range(diff):
headB = headB.next
if headA == headB:
return headA
while headA.next != None:
if headA.next == headB.next:
return headA.next
headA = headA.next
headB = headB.next
return None
# 计算长度就完事了!