Hi All,
In below code i am performing search in map through key value but not able to get the desire results though common elements (intersection) is present in both lists.

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <map>
using namespace std;

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

/* A utility function to insert a node at the beginning of 
   a linked list*/
void push(struct node** head_ref, int new_data);






/* A utility function to insert a node at the begining of a linked list*/
void push (struct node** head_ref, int new_data)
{
    /* allocate node */
    struct node* new_node =
        (struct node*) malloc(sizeof(struct node));

    /* put in the data */
    new_node->data = new_data;

    /* link the old list off the new node */
    new_node->next = (*head_ref);

    /* move the head to point to the new node */
    (*head_ref) = new_node;
}





int create_hash(struct node* head1,struct node* head2)
{
  int flag=0;
 map<node*,bool> intersect;
    //intersect.insert(make_pair("Peter Q.",5328));
while(head1!=NULL)
{
printf("first_list->data=%d\n",head1->data);
intersect[head1]=true;
head1=head1->next;

}

while(head2!=NULL)
{

printf("second_list->data=%d\n",head2->data);

if (intersect.find(head2)!= intersect.end())
       printf("common->data=%d\n",head2->data); 
       flag=1;
       head2=head2->next;

}
if(flag==1)
{
return 0;
}
return -1;
}


/* Drier program to test above function*/
int main()
{
    /* Start with the empty list */


    struct node* head1 = NULL;
    struct node* head2 = NULL;
    int ret_val;
    struct node* unin = NULL;

    /*create a linked lits 10->15->5->20 */
    push (&head1, 20);
    push (&head1, 4);
    push (&head1, 15);
    push (&head1, 10);

    /*create a linked lits 8->4->2->10 */
    push (&head2, 10);
    push (&head2, 2);
    push (&head2, 4);
    push (&head2, 8);
  ret_val = create_hash (head1, head2);

    return 0;
}

Recommended Answers

All 2 Replies

It looks to me that a node from one tree will never equal the node from another tree, since even if the data is the same, next won't be. You might need your own search function, something like this:

node* FindNode(node* tree, node* element)
{
    while(tree != NULL)
    {
        if (tree->data == element->data)
        {
            return tree;
        }
        tree = tree->next;
    }
    return NULL;
}

This will return the node in the tree with data that equals the data in element, or NULL if none is found.

I think Tinstaffl is correct on this note.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.