vendredi 28 janvier 2022

Why the given code(Program to remove duplicates from a linked list using hashing) is not displaying any output?

#include <iostream>
#include <unordered_map>

using namespace std;

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

unordered_map<int,int> hashmap;

Node* head = NULL;



void deldups()
{
    Node* h = head;
    Node* prev = NULL;
    Node* curr;
    curr = h;
    
    while(curr != NULL)
    {
        int val = curr -> data;
        if (hashmap.find(val) != hashmap.end())
        {
            if(hashmap[val] > 1)
            {
            prev -> next = curr -> next -> next;
            delete(curr);
            }
        }
        else{
            ++hashmap[val];
            prev = curr;
        }
        curr = prev->next;
    }
}

void print()
{
    Node* temp = head;
    while(temp != NULL)
    {
        cout << temp -> data << " ";
        temp = temp->next;
    }
}

int main() 
{
    Node* firstnode = new Node();
    head = firstnode;
    firstnode -> data = 5;
    Node* secondnode = new Node();
    firstnode -> next = secondnode;
    secondnode -> data = 6;
    Node* thirdnode = new Node();
    secondnode -> next = thirdnode;
    thirdnode -> data = 7;
    Node* forthnode = new Node();
    thirdnode -> next = forthnode;
    forthnode -> data = 5;
    Node* fifthnode = new Node();
    forthnode -> next = fifthnode;
    fifthnode -> data = 9;
    fifthnode -> next = NULL;
    

    deldups();
    print();
    return 0;
}

I want to write a program that will remove duplicates from the linked list and print the linked list. I have used the hashing method to achieve this,

Code Explanation:

  1. Traverse the linked list while ptr is not NULL

check if the given element (h -> data) is present in the map 'key' (unordered<int,int>) NOTE I am using the element as a key in the map and not its value, value will be used to count its duplicates.

again,


  1. if the key is present then we will check its value and if the value is greater than '1' i.e the element is present more than one time then remove the node from the linked list
  2. else, add the element key into the hashmap and increment its value by one.

After running the code there is no output. why?

Aucun commentaire:

Enregistrer un commentaire