-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathp2_2.py
More file actions
32 lines (24 loc) · 758 Bytes
/
p2_2.py
File metadata and controls
32 lines (24 loc) · 758 Bytes
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
from chapter_2.linked_list_utils import *
# Method: Leader and follower pointer, at k distance
# Time: O(n)
# Space: O(1)
def k_to_last(k: int, head: Node):
leader_ptr = head
follower_ptr = head
distance = -1
while leader_ptr:
print(f"Leader is {leader_ptr} "
f"and follower {follower_ptr},"
f" at distance {distance}")
distance += 1
if distance > k:
follower_ptr = follower_ptr.next
leader_ptr = leader_ptr.next
if distance < k:
raise Exception(f"Input too short for distance {distance}")
return follower_ptr.val
if __name__ == "__main__":
ex1 = link_list_of_list([1, 2, 3, 4, 5, 6, 7])
d = 5
print(ex1)
print(k_to_last(d, ex1))