【发布时间】:2020-04-24 22:30:57
【问题描述】:
我想编写一个函数来获取与作为参数传递的键的后继键关联的数据。我想编写它以尽可能简单地执行操作,除了到目前为止遇到一些错误之外,我想要一些关于如何修复我的代码的建议,以便它这样做。我想要建议的方法是 GetSuccessor(Comparable key)。
class HashTable
{
int size;
int length;
Node nodes[];
// Constants
static final double max_load_factor = 0.7;
static final int initial_size = 5;
public HashTable()
{
size = initial_size;
nodes = new Node[size];
}
// Return the data associated with the given key, or null if the key
// is not present in the hash table.
public Object Search(Comparable key)
{
// Obtain index for the key
int index = key.hashCode() % size;
// Traverse collision list
for (Node node = nodes[index]; node != null; node = node.next)
if (node.key.equals(key))
return node.data;
// Not found
return null;
}
// Insert a pair key-data into the hash table
public void Insert(Comparable key, Object data)
{
// Check if the table must grow
double load_factor = (double) length / size;
if (load_factor > max_load_factor)
Grow();
// Create node
Node node = new Node(key, data);
// Get index for the key
int index = key.hashCode() % size;
// Insert node
node.next = nodes[index];
nodes[index] = node;
//Update length
length++;
}
// Grow the hash table. All node must be repositioned according
// to their new flash indices based on the new table.
void Grow()
{
// Message
System.out.println("Growing hash table");
// Save old nodes and table siz4
int old_size = size;
Node[] old_nodes = nodes;
// Create new table
size = size * 2;
length = 0;
nodes = new Node[size];
// Traverse old nodes
for (int i = 0; i < old_size; i++)
for (Node node = old_nodes[i]; node != null; node = node.next)
Insert(node.key, node.data);
}
// Return the data associated with the successor for the given key,
// or null if the key is the last or it is not present.
public Object GetSuccessor(Comparable key)
{
// Find node
Node node = Search(key);
if (node == null)
return null;
// Get sucessor node
for (Node node = nodes[key.hashCode()]; node != null; node = node.next)
if (node.key.equals(key))
return node.next.data;
// Return associated data
return node == null ? null : node.next.data;
}
}
【问题讨论】:
-
哈希表是无序的。由此可见,没有继任者之类的东西。如果您想要顺序和继任者,请使用有序映射:
TreeMap。 -
我的意思是如果 12 作为参数传递,则与键 13 关联的数据
-
我明白你的意思;我已经表明它是没有意义的;我提供了一个替代解决方案。