minimanimoh / Udacity_DS-A

0 stars 0 forks source link

DS&A - 2. Data Structures - Lesson 1. Detecting Loops in Linked Lists #9

Open minimanimoh opened 3 years ago

minimanimoh commented 3 years ago
class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

class LinkedList:
    def __init__(self, init_list=None):
        self.head = None
        if init_list:
            for value in init_list:
                self.append(value)

    def append(self, value):
        if self.head is None:
            self.head = Node(value)
            return

        # Move to the tail (the last node)
        node = self.head
        while node.next:
            node = node.next

        node.next = Node(value)
        returnv

list_with_loop = LinkedList([2, -1, 3, 0, 5])
​
# Creating a loop where the last node points back to the second node
loop_start = list_with_loop.head.next
​
node = list_with_loop.head
while node.next: 
    node = node.next   
node.next = loop_start

def iscircular(linked_list):
    """
    Determine whether the Linked List is circular or not

    Args:
       linked_list(obj): Linked List to be checked
    Returns:
       bool: Return True if the linked list is circular, return False otherwise
    """

    # TODO: Write function to check if linked list is circular
    if linked_list.head is None:
        return False

    slow = linked_list.head
    fast = linked_list.head

    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next

        if slow == fast:
            return True
    return False