Sunday, January 5, 2014

Detecting start of the loop in circular singly linked list

Consider a single linked list as below which has a loop at node 5.


As discussed in the last post we can detect if there is loop present in the list or not with use of the two pointers. To find out the start of the loop we will have to follow the same strategy. 

As we are traversing some x nodes before starting the loop hence the far and near pointer will meet at x nodes less location in the loop. If we traverse x nodes from start and x nodes from where the two pointers meet we can detect the start of the loop. 

The code below uses the same technique discussed above to detect the start of the loop in circular single linked list.



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


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

    while (pHead != NULL && pFar !=NULL)
    {
        pFar = pFar->pNext;

        if (pFar)
            pFar = pFar->pNext;
        else
            return NULL;

        pHead = pHead->pNext;

        if (pFar == pHead)
        {
            return pFar;
        }
    }
    return NULL;
}

Node * FindStartOfLoop(Node *pHead)
{
    Node * pTemp = IsListCircular(pHead);

    if (pTemp)
    {
        while (pTemp != pHead)
        {
            pHead = pHead->pNext;
            pTemp = pTemp->pNext;
        }

        return pHead;
    }

    return NULL;
}

The function FindStartOfLoop will return the address of the start node of the loop else will return NULL.

No comments:

Post a Comment