-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path160_intersection_of_two_linked_lists
56 lines (50 loc) · 1.42 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
45
46
47
48
49
50
51
52
53
54
55
56
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# hash table
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
currA = headA
currB = headB
node_seen = set()
while currA:
node_seen.add(currA)
currA = currA.next
while currB:
if currB in node_seen:
return currB
else:
currB = currB.next
return None
# 2 pointers
class Solution:
# @param two ListNodes
# @return the intersected ListNode
def getIntersectionNode(self, headA, headB):
curA, curB = headA, headB
lenA, lenB = 0, 0
while curA != None:
lenA += 1
curA = curA.next
while curB != None:
lenB += 1
curB = curB.next
curA, curB = headA, headB
if lenA > lenB:
for i in range(lenA-lenB):
curA = curA.next
elif lenA < lenB:
for i in range(lenB-lenA):
curB = curB.next
while curA != curB:
curA = curA.next
curB = curB.next
else:
return curA
return None