Tuesday, January 19, 2021

detect a loop in linked list using hashing

1. HASHING
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
//hashing to detect a  loop in a linklist

struct node{
    int data; struct node* next;
};

void push(struct node** head_ref, int new_data)
{
    struct node* new_node= new node(); new_node->data= new_data;
    new_node->next= (*head_ref); (*head_ref)= new_node;
} //f ends

//returns true if a loop is detected
bool detectloop(struct node* hash)
{
    unordered_set<node*> set;
    while(hash!=NULL) {
        if (set.find(hash)!=set.end()) return true;
        set.insert(hash); //if we are visiting a new node , insert in hash
        hash= hash->next;
        
    } //while ends
    return false;
} //bool ends

int main() {
 struct node* head= NULL; //start with empty linkedlist
 push(&head, 20);
  push(&head, 4);
   push(&head, 15);
    push(&head, 10);
 
   //create a loop for testing
   head->next->next->next->next=head;
   if(detectloop(head)) cout<< "Loop found";
   else cout<< "No loop here";
return 0;
}

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home