8000 Contains loops.py add by kanthuc · Pull Request #2442 · TheAlgorithms/Python · GitHub
[go: up one dir, main page]

Skip to content

Contains loops.py add #2442

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Sep 18, 2020
Merged
Prev Previous commit
Next Next commit
added doctests and clarified meaning of loop
  • Loading branch information
kanthuc committed Sep 18, 2020
commit d37fd6e706abdd5c3c0729aeeb6058c6ea876738
23 changes: 20 additions & 3 deletions data_structures/linked_list/contains_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,25 @@ def __init__(self, data: Any) -> None:

def contains_loop(root: Node) -> bool:
"""
given a node, returns true if linked list contains a loop
A linked list contains a loop when traversing through a loop, no null is reached.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This explanation is still unclear to me. What is a null in this context?


Given a node, returns true if linked list contains a loop
returns false otherwise

>>> node1 = Node(1)
>>> node1.next_node = Node(2)
>>> node1.next_node.next_node = Node(3)
>>> node1.next_node.next_node.next_node = Node(4)
>>> node1.next_node.next_node.next_node = node1.next_node
>>> contains_loop(node1)
True

>>> node2 = Node(1)
>>> node2.next_node = Node(2)
>>> node2.next_node.next_node = Node(1)
>>> node2.next_node.next_node.next_node = Node(2)
>>> contains_loop(node2)
False
"""

counter1 = root
Expand All @@ -40,8 +57,8 @@ def contains_loop(root: Node) -> bool:

node2 = Node(5)
node2.next_node = Node(6)
node2.next_node.next_node = Node(7)
node2.next_node.next_node.next_node = Node(8)
node2.next_node.next_node = Node(5)
node2.next_node.next_node.next_node = Node(6)
print(contains_loop(node2))

node3 = Node(1)
Expand Down
0