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.

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;
}