2016-05-05 6 views
1

以下のコードでは、キー値でマップを検索していますが、両方のリストに共通の要素がありますが、目的の結果を得ることができませんマップは期待される出力を与えるはずです。 地図で検索する際に問題はありますか?それは正しいアプローチですか?キー値の検索機能によるマップ内検索が正しく行われていません

入力

LIST1:10-> 15-> 4-> 20 LIST2:10-> 2-> 4-> 8

期待出力: コモン>データの共通= 4 - >データ= 10

#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; 
    } 
    /*insert the head1 into map and find the head2 in map*/ 
    int create_hash(struct node* head1,struct node* head2) 
    { 
     int flag=0; 
    map<node*,bool> intersect; 

    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->4->20 */ 
     push (&head1, 20); 
     push (&head1, 4); 
     push (&head1, 15); 
     push (&head1, 10); 
     /*create a linked list 10->2->4->8 */ 
     push (&head2, 10); 
     push (&head2, 2); 
     push (&head2, 4); 
     push (&head2, 8); 
     ret_val = create_hash (head1, head2); 
     return 0; 
    } 
+0

これはCコードと小さなC++の混合物です。これは主な問題です –

答えて

1

あなたは、ノードリストの最初にからポインタとintersectマップを移入した後、第二のリスト内のノードへのポインタのためにそのマップを検索します。ノードはリスト間で共有されないので、検索は決して成功しません。

この実装のコンテキストでは、マップにはノードポインタではなくデータ値が含まれている必要があります。

+0

あなたの返事をありがとう。現在の共有コードを変更してノードベースの検索を実行できるかどうかは、とにかくありますか? – user2997518

+0

map intersect;私の問題を解決するだろうが、マップで同じものを解決するには? – user2997518

+0

'intersect.find(head2)'の代わりに 'std :: find_if(intersect.begin)、intersect.end()、[head2](node * n){return n-> data == head2- >データ;}) '。 (C++ 11ラムダを使用できない場合は、同等ですがより冗長な構造があります)。 – Jeremy

関連する問題