想一种添加对应于表的每个哈希地址的计数器的方法?

时间:2015-12-10 23:37:04

标签: c++ c++11 data-structures linked-list hashmap

我正在使用链表创建一个哈希表,我让表工作正常,但我需要为表中的每个地址创建一个计数器。

程序必须跟踪表中每个地址的当前冲突计数。为此,每个地址必须有一个计数器。地址为0 .. tableSize-1。每次程序插入一个元素时,它必须递增对应于元素的哈希地址的计数器。类似地,每当从表中删除元素时,必须递减对应于元素的散列地址的计数器。

我应该将一个变量添加到我的列表或散列表中以保持跟踪。我不想包含太多代码以使事情变得混乱所以我将包括来自我的linkedList.cpp和Hashtable.cpp的片段。

Hashtable.cpp

#include "HashTable.h"

// Constructs the empty Hash Table object.
// Array length is set to 13 by default.
HashTable::HashTable( int tableLength )
{
if (tableLength <= 0) tableLength = 13;
array = new LinkedList[ tableLength ];
length = tableLength;
}

// Returns an array location for a given item key.
int HashTable::hash( string itemKey )
{
int hashAddress=0;


for ( int i = 0; i < itemKey.length(); i++ )
   hashAddress= atoi(itemKey.c_str());
return (hashAddress  ) % length;
}

// Adds an item to the Hash Table.
void HashTable::insertItem( Item * newItem )
{
int index = hash( newItem -> key );
array[ index ].insertItem( newItem );
}

// Deletes an Item by key from the Hash Table.
// Returns true if the operation is successful.
bool HashTable::removeItem( string itemKey )
{
int index = hash( itemKey );
return array[ index ].removeItem( itemKey );
}

// Returns an item from the Hash Table by key.
// If the item isn't found, a null pointer is returned.
Item * HashTable::getItemByKey( string itemKey )
{

。 。

Linklist.cpp

#include "LinkedList.h"

// Constructs the empty linked list object.
// Creates the head node and sets length to zero.
LinkedList::LinkedList()
  {
   head = new Item;
   head -> next = NULL;
   length = 0;
}

// Inserts an item at the end of the list.
void LinkedList::insertItem( Item * newItem )
{
if (!head -> next)
{
    head -> next = newItem;
    length++;
    return;
}
Item * p = head;
Item * q = head;
while (q)
{
    p = q;
    q = p -> next;
}
p -> next = newItem;
newItem -> next = NULL;
length++;
}

// Removes an item from the list by item key.
// Returns true if the operation is successful.
bool LinkedList::removeItem( string itemKey )
{
if (!head -> next) return false;
Item * p = head;
Item * q = head;
while (q)
{
    if (q -> key == itemKey)
    {
        p -> next = q -> next;
        delete q;
        length--;
        return true;
    }
    p = q;
    q = p -> next;
}
return false;
}

// Searches for an item by its key.
// Returns a reference to first match.
// Returns a NULL pointer if no match is found.
Item * LinkedList::getItem( string itemKey )

。 。

1 个答案:

答案 0 :(得分:0)

正如评论中已经提到的那样,您已经维持了这样一个计数器。您所要做的就是创建一个新方法来获取变量。您可以在实现&#39; LinkedList&#39;的文件中的这些行上实现某些功能。方法。

int LinkedList::getCounter(int address)
{
   if(address>length)//referring to length of HashTable class
      return -1;
   return array[address].length;
}