Benutzer:Riemer
Aus ProgrammingWiki
Wiki-Quelltext dieser Seite.
<language>Java</language>
<popup name="Klassen-Definitionen">
<code id="4f6a410984ee7">
public Object Link(int d) {
int data = d;
Object next;
public int getKey() {
return data;
}
public void displayLink() {
System.out.print(data + " ");
}
return this;
}
public Object List() {
Object first = null;
public void insert(Object theLink) {
Object previous = null;
Object current = first;
while (current != null) {
previous = current;
current = current.next;
}
if (previous == null) {
first = theLink;
} else {
previous.next = theLink;
}
theLink.next = current;
}
public void delete(int key) {
Object previous = null;
Object current = first;
while (current != null && key != current.getKey()) {
previous = current;
current = current.next;
}
if (previous == null) {
first = first.next;
} else {
previous.next = current.next;
}
}
public Object find(int key) {
Object current = first;
while (current != null) {
if (current.getKey() == key) {
return current;
}
current = current.next;
}
return null;
}
public void displayList() {
System.out.print("List: ");
Object current = first;
while (current != null) {
current.displayLink();
current = current.next;
}
System.out.println("");
}
return this;
}
public Object HashChain(int size) {
private int arraySize = size;
private Object[] hashArray = new Object[arraySize];
for (int i = 0; i < arraySize; i++) {
hashArray[i] = List();
}
public void displayTable() {
for (int j = 0; j < arraySize; j++) {
System.out.print(j + ". ");
hashArray[j].displayList();
}
}
public int hashFunc(int key) {
return key % arraySize;
}
public void insert(theLink) {
int key = theLink.getKey();
int hashVal = hashFunc(key);
hashArray[hashVal].insert(theLink);
}
public void delete(int key) {
int hashVal = hashFunc(key);
hashArray[hashVal].delete(key);
}
public Object find(int key) {
int hashVal = hashFunc(key);
Object theLink = hashArray[hashVal].find(key);
return theLink;
}
return this;
}
</code>
</popup>
<run id="4f6a4158b8217">
int aKey;
int size, initSize, keysPerCell = 10;
size = 20;
initSize = 10;
hashTable = HashChain(size);
for (int i = 0; i < initSize; i++) {
aKey = (int) (java.lang.Math.random() * keysPerCell * size);
dataItem = Link(aKey);
hashTable.insert(dataItem);
}
aKey = 100;
dataItem = Link(aKey);
hashTable.insert(dataItem);
// aKey = 100;
// hashTable.delete(aKey);
hashTable.displayTable();
aKey = 100;
dataItem = hashTable.find(aKey);
if (dataItem != null) {
System.out.println("Found " + aKey);
} else {
System.out.println("Could not find " + aKey);
}
</run>