2016-11-20 23 views
1

私は自分自身のHashTableクラスをC++で作成しており、テーブル内の各文字列の出現回数をユーザに出力する必要があります。これは入力された場合、例えば:testing, 1, 2, testing、これはハッシュテーブルである(連鎖で行われ、ノードポインタ):これは、ユーザー(カウントに出力あろうハッシュテーブル内の文字列の出現回数をカウントする

[0]->testing, testing 
[1]->2 
[2]->1 

は、単語に続きます):

2 testing 
1 2 
1 1 

私がいる問題は、ハッシュテーブルにあるか、どのようにそれを見つける方法を各単語の多くを追跡する方法です。私はthis questionで始まりましたが、私のコードで別の配列を実装できませんでした。

私もthis questionで解決策を試しましたが、ポインタ/連鎖ハッシュを使用していたために機能しませんでした。

私の質問は、既に使用されているものを追跡するために別の文字列を使用する必要があるのか​​、再帰的にハッシュテーブルの各インデックスを調べて出現回数を出力する簡単な方法です各文字列の?私は私のinsert機能か私のprintData機能でこれを達成する必要があると思う。

HashTable.h

#include <string> 
#include <iostream> 

using namespace std; 

struct Entry { 
    string word; 
    Entry* next; 
}; 

class HashTable { 
public: 
    HashTable(); 
    HashTable(int); 
    int hash(string); 
    void insert(string); 
    void printData(); 
    int getCapacity() const; 
private: 
    //Member variables 
    int CAPACITY; // The initial capacity of the HashTable 
    Entry **data; // The array to store the data of strings (Entries) 
}; 

HashTable.cpp:参考

は、ここに私のコードです

#include "HashTable.h" 

HashTable::HashTable() 
{ 
    CAPACITY = 0; 
    data = new Entry*[0]; 
} 

HashTable::HashTable(int _cap) 
{ 
    CAPACITY = _cap; 
    data = new Entry*[_cap]; 

    for (int i = 0; i < CAPACITY; i++) { 
     data[i] = new Entry; 
     data[i]->word = "empty"; 
     data[i]->next = nullptr; 
    } 
} 

int HashTable::hash(string key) 
{ 
    int hash = 0; 

    for (unsigned int i = 0; i < key.length(); i++) { 
     hash = hash + (int)key[i]; 
    } 

    return hash % CAPACITY; 
} 

void HashTable::insert(string entry) 
{ 
    int index = hash(entry); 

    if (data[index]->word == "empty") { 
     data[index]->word = entry; 
    } else { 
     Entry* temp = data[index]; 
     Entry* e = new Entry; 
     e->word = entry; 
     e->next = nullptr; 

     while (temp->next != nullptr) { 
      temp = temp->next; 
     } 

     temp->next = e; 
    } 
} 

void HashTable::printData() 
{ 
    for (int i = 0; i < CAPACITY; i++) { 
     if (data[i]->next != nullptr) { 
      while(data[i]->next != nullptr) { 
       cout << data[i]->word << " -> "; 
       data[i] = data[i]->next; 
      } 

      cout << data[i]->word << endl; 
     } else { 
      cout << data[i]->word << endl; 
     } 
    } 
} 

int HashTable::getCapacity() const 
{ 
    return CAPACITY; 
} 

注:私は、標準Cから任意の関数/データ構造を使用することはできません++としょうかん。

答えて

2

私は唯一の回出てくるカウントするために、ここで二つのオプション全体のリンクリストトラバース

  1. を参照してください。 < string、int>マップを使用して、各文字列の出現を数えます。

  2. リンクリストをソートする必要があります。したがって、新しいノードを挿入すると、そのノードを正確な場所に挿入します。比較のためにstrcmpを使用することができます。この方法で、すべての単語を1回のトラバースで正確にカウントし、整数変数を1つだけ使用できますが、挿入時間と複雑さが増します。

関連する問題