DEV Community

Justin Bermudez
Justin Bermudez

Posted on

Finding a Loop in a Singly Linked List in Python

Given the head of a Singly Linked List that contains a loop, which is the list's tail points to some node in the list instead of none.

Given a standard class of Linked List

class LinkedList:
    def __init__(self, value):
        self.value = value
        self.next = None
Enter fullscreen mode Exit fullscreen mode

When we look through the Linked List we should return where the loop returns us too. So after our tail node, we return what comes after that.

We look at 2 nodes at a time moving at different speeds. If the nodes ever equal each other, then that is where our loop is.

def findLoop(head):
    first = head.next
    second = head.next.next
    while first != second:
        first = first.second
        second = second.next.next
    while first != second:
        first = first.next
        second = second.next
    return first
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Image of PulumiUP 2025

Transform Your Cloud Infrastructure

Join PulumiUP 2025 on May 6 for Expert Insights & Demos.

Register Now

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay