簡體   English   中英

正在考慮添加與表的每個哈希地址相對應的計數器的方法?

[英]Thinking of a way to add a counter corresponding to each hash address of the table?

我正在使用鏈表創建哈希表,表工作正常,但是我需要為表中的每個地址創建一個計數器。

程序必須跟蹤表中每個地址的當前沖突計數。 為此,每個地址必須有一個計數器。 地址為0 .. tableSize-1。 每次程序插入一個元素時,它都必須遞增與該元素的哈希地址相對應的計數器。 同樣,每當從表中刪除元素時,與該元素的哈希地址相對應的計數器都必須遞減。

我是否應該在列表或哈希表中添加變量以保持跟蹤。我不想包含太多代碼,以免使事情變得混亂,因此我將包含來自LinkedList.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 )
{

鏈接列表

#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 )

正如評論中已經提到的那樣, 您已經在維護這樣一個計數器 您要做的就是創建一個獲取該變量的新方法。 您可以在實現“ LinkedList”方法的文件的這些行上實現某些功能。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM