Beispiel #1
0
static void _AddKeyValuePair(struct HashTable *table, char *key, void *value)
{
	tindex_t index = _HashFunction(key, table->hashLimit);
	// Do the nice way
	bool empty = _IsElementAtIndexEmpty(table, index);
	if (empty)
	{
		_SetKeyValuePairAtIndex(table, key, value, index);
	} else
			// Otherwise do collision way
	{
		index = _FindEmptyIndexAfterIndex(table, index);
		if (index == -1)
			return;

		_SetCollisionKeyValuePairAtIndex(table, key, value, index);
	}

	tindex_t successfullyAddedIndex = _FindExistingIndexForKey(table, key);
	if (successfullyAddedIndex == -1)
		return;

	lst_SetValueForKey(table->iteratorKVList, index, key);
	if (lst_ValueForKey(table->iteratorKVList, key) != index)
	{
		_RemoveKeyValuePairAtIndex(table, index);
	}

}
		/// 向散列表中插入一个元素
		void Insert( T const &new_value )
		{
			//始终插入在键表的头,头结点之后的第1个位置
			_Node *new_item = new _Node;
			new_item->Item = new_value;
			new_item->Next = nullptr;
			int hash_value = _HashFunction( new_value );

			new_item->Next = _items[hash_value]->Next;
			_items[hash_value]->Next = new_item;
		}
		/// 在散列表中搜索一个元素
		T * Search( T const &search_value )
		{
			int hash_value = _HashFunction( search_value );
			_Node *root = _items[hash_value]->Next;

			while ( root )
			{
				if ( root->Item == search_value )
				{
					return &( root->Item );
				}
				root = root->Next;
			}
			return nullptr;
		}
Beispiel #4
0
static tindex_t _FindExistingIndexForKey(struct HashTable *table, char *key)
{
	// Search in hash index
	tindex_t desiredIndex = _HashFunction(key, table->hashLimit);
	bool containsDesiredElement = _IsElementAtIndexForKey(table, desiredIndex, key);
	if (containsDesiredElement != 0)
		return desiredIndex;

	// Search in collisions
	struct KeyValueList *collisionList = table->collisionsList;
	tindex_t collisionIndex = lst_ValueForKey(collisionList, key); // Will return -1 if not found
	if (collisionIndex != -1)
		return collisionIndex;

	return -1;
}
		/// @brief 从散列表中删除一个元素
		///
		/// @return	是否成功的删除这样的元素
		bool Delete( T const &delete_value )
		{
			int hash_value = _HashFunction( delete_value );
			_Node *root = _items[hash_value];

			while ( root->Next )
			{
				if ( root->Next->Item == delete_value )
				{
					auto temp = root->Next;
					root->Next = root->Next->Next;
					delete temp;
					return true;
				}
				else
				{
					root = root->Next;
				}
			}

			return false;
		}