Click here to Skip to main content
15,892,697 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have created a linked list and I want to create a loop in it which I can detect, but when I write "temp->next->next->next=temp->next->next" it goes infinite. I don't understand why is it like that, I don't call that function recursively that can result in that kind of things.

#include <iostream>
#include <unordered_set>



class linkedList
{
private:
    struct node
    {
        int data;
        node *next;
    };
    node *head;

public:
    linkedList():head(nullptr)
    {

    }
    ~linkedList()
    {
        cleanUp(head);
    }
    void cleanUp(node *temp);
    void _push(node *&temp, int key);
    void push(int key)
    {
        _push(head, key);
    }

    void _print(node *temp);
    void print()
    {
        _print(head);
    }

    bool detectLoop(node *&temp);
    void loop()
    {
        std::cout<<detectLoop(head)<<std::endl;
    }
    void makeLoop(node *temp);
    void made()
    {
        makeLoop(head);
    }
};

void linkedList::_push(node *&temp, int key)
{
    node *newNode=new node;
    newNode->data=key;
    newNode->next=temp;
    temp=newNode;
}

void linkedList::cleanUp(node *temp)
{
    while(temp)
    {
        node *it=temp;
        temp=temp->next;
        delete it;
    }
}

bool linkedList::detectLoop(node *&temp)
{

    if(temp==nullptr || temp->next== nullptr)
    {
        return false;
    }

    node *first=temp;
    node *second=temp->next;

    while(second!= nullptr)
    {
        if(first==second)
        {
            return true;
        }

        first=first->next;
        second=second->next->next;
    }


}

void linkedList::makeLoop(node* temp)
{
    temp->next->next->next=temp->next->next;
}

void linkedList::_print(node *temp)
{
    while(temp)
    {
        std::cout<<temp->data<<" ";
        temp=temp->next;
    }
}



int main()
{
    linkedList l;
    l.push(7);
    l.push(8);
    l.push(1);
    l.push(7);

    l.made();

    l.loop();

    l.print();

}


What I have tried:

I have tried to understand it with debugger
Posted
Updated 16-Jan-18 21:51pm

Your code correctly detects the loop then iterate endlessly because the print method itself faces the loop.
 
Share this answer
 
Comments
Member 13277493 17-Jan-18 4:17am    
thanks!
CPallini 20-Jan-18 4:55am    
You are welcome.
That because temp->next->next now points to itself...
Let say that a is temp->next->next...
now you set a->next = a...
 
Share this answer
 
v2
Comments
Member 13277493 17-Jan-18 3:47am    
That means I must connect the end node of the loop to nullptr, am I right?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900