Mohit Soni
Mohit Soni

Reputation: 11

Below is the code I made for detecting cycle in link list?

where I used two counters one counter is where the head pointer has reached till now and another counter goes from start to one position less than the position where the head is present to find a similar node but this code does not work why?

bool has_cycle(Node* head) {
    // Complete this function
    // Do not write the main method
    int i=0,j=0;
    struct Node* temp=head;
    while(head!=NULL){
        i=0;
        while(i<j){
            if(temp==head){
                return true;
            }
            temp=temp->next;
            i++;
        }
        j++;
        head=head->next;
    }
    return false;
}

Upvotes: 0

Views: 26

Answers (1)

Mohit Soni
Mohit Soni

Reputation: 11

After getting the help from David C. Rankin's answer I made the below code and it works well.

bool has_cycle(Node* head) {
    // Complete this function
    // Do not write the main method
    int i=0,j=0;
    struct Node* temp=head;
    struct Node* temp1=head;
    while(head!=NULL){
        i=0;
        while(i<j){
            if(temp==head){
                return true;
            }
            temp=temp->next;
            i++;
        }
        temp=temp1;
        j++;
        head=head->next;
    }
    return false;
}

Upvotes: 1

Related Questions