Thursday, January 2, 2014

Detecting loop in singly linked list

To detect loop in the circular singly linked list you will need two pointers. One near pointer and one far pointer.

Far pointer you will increment by two nodes where as near pointer you will increment by one so that if there is loop in the link list at some point both pointer will point to the same node. 

The code uses the similar technique.



struct Node
{
    int data;
    Node * pNext;
};


bool IsListCircular(Node * pHead)
{
    Node* pFar = pHead;

    bool bHasLoop = false;

    while (pHead != NULL)
    {
        if (pFar)
            pFar = pFar->pNext;
        else
            break;

        if (pFar)
            pFar = pFar->pNext;
        else
            break;

        pHead = pHead->pNext;

        if (pFar == pHead)
        {
            bHasLoop = true;
            break;
        }

    }
    return bHasLoop;
}



No comments:

Post a Comment