My program is meant to take a list of words and store each word under a letter reference in an array in ascending order. For example array of A-Z words apple, ape under a linked list under A referenced by 0, Zebra under Z referenced by 25. But when I use the standard first = new Node(word) I am not adding anything. I'm hopelessly lost.
import java.util.LinkedList;
public class ArrayLinkedList
{
/**
The Node class is used to implement the
linked list.
*/
private class Node
{
String value;
Node next;
/**
* Constructor
* #param val The element to store in the node
* #param n The reference to the successor node
*/
Node(String val, Node n)
{
value = val;
next = n;
}
Node(String val)
{
this(val, null);
}
}
private final int MAX = 26; // Number of nodes for letters
private Node first; // List head
private Node last; // Last element in the list
private LinkedList[] alpha; // Linked list of letter references
/**
* Constructor to construct empty array list
*/
public ArrayLinkedList()
{
first = null;
last = null;
alpha = new LinkedList[MAX];
for (int i = 0; i < MAX; i++)
{
alpha[i] = new LinkedList();
}
}
/**
* arrayIsEmpty method
* To check if a specified element is empty
*/
public boolean arrayIsEmpty(int index)
{
return (alpha[index].size() == 0);
}
/**
* The size method returns the length of the list
* #return The number of elements in the list
*/
public int size()
{
int count = 0;
Node p = first;
while (p != null)
{
// There is an element at p
count++;
p = p.next;
}
return count;
}
/**
* add method
* Adds the word to the first position in the linked list
*/
public void add(String e)
{
String word = e.toLowerCase(); // Put String to lowercase
char c = word.charAt(0); // to get first letter of string
int number = c - 'a'; // Index value of letter
// Find position of word and add it to list
if (arrayIsEmpty(number))
{
first = new Node(word);
first = last;
}
else
{
first = sort(first, word, number);
}
}
/**
* nodeSort method
* To sort lists
*/
private Node sort(Node node, String value, int number) {
if (node == null) // End of list
{
return getNode(value, number);
}
int comparison = node.value.compareTo(value);
if (comparison >= 0) // Or > 0 for stable sort.
{
Node newNode = getNode(value, number); // Insert in front.
newNode.next = node;
return newNode;
}
node.next = sort(node.next, value, number); // Insert in the rest.
return node;
}
private Node getNode(String value, int number)
{
return first.next;
}
/**
* get method
* to get each word value from the linked list and return it
* #return value
*/
public LinkedList get(int index)
{
return alpha[index];
}
public String toString()
{
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("Word and occurrence in ascending order\n\n");
Node p = first;
while (p != null)
{
sBuilder.append(p.value + "\n");
p = p.next;
}
return sBuilder.toString();
}
}
Is there a reason you are doing it this way.
I can think of an easier way: use Map which will map a character (e.g. "A") to a LinkedList of Words.
Related
I am trying to implement the set method where you pass in the position in a linked list that you want and the value and the set function adds that value into the position specified in the linked list. I have implemented the set function but for some reason The last element disappears in my implementation. I would greatly appreciate any help. Thanks in advance. I would appreciate any expert eyes that will see what I am missing.
/**
* A basic singly linked list implementation.
*/
public class SinglyLinkedList<E> implements Cloneable, Iterable<E>, List<E> {
//---------------- nested Node class ----------------
/**
* Node of a singly linked list, which stores a reference to its
* element and to the subsequent node in the list (or null if this
* is the last node).
*/
private static class Node<E> {
E value;
Node<E> next;
public Node(E e)
{
value = e;
next = null;
}
}
//----------- end of nested Node class -----------
// instance variables of the SinglyLinkedList
private Node<E> head = null; // head node of the list (or null if empty)
private int size = 0; // number of nodes in the list
public SinglyLinkedList() {
} // constructs an initially empty list
// access methods
/**
* Returns the number of elements in the linked list.
*
* #return number of elements in the linked list
*/
public int size() {
return size;
}
/**
* Adds an element to the end of the list.
*
* #param e the new element to add
*/
public void addLast(E e) {
// TODO
}
/**
* Tests whether the linked list is empty.
*
* #return true if the linked list is empty, false otherwise
*/
public boolean isEmpty() {
return size == 0;
}
#Override
public E get(int i) throws IndexOutOfBoundsException {
Node<E> a = head;
if(i<=this.size()) {
int count = 0;
while(count < i) {
count ++;
a = a.next;
}
return a.value;
}
return null;
}
#Override
public E set(int i, E e) throws IndexOutOfBoundsException {
Node<E> current = head;
Node<E> setNode = new Node<E>(e);
if(i==0) {
this.addFirst(e);
}
else if(i==this.size){
this.addLast(e);
}
else {
for(int j=0; current != null && j < (i-1);j++) {
current = current.next;
}
Node<E> temp = current.next;
current.next = setNode;
setNode.next = temp;
}
return setNode.value;
}
// update methods
/**
* Adds an element to the front of the list.
*
* #param e the new element to add
*/
public void addFirst(E e) {
Node<E> first = new Node<>(e);
first.next = this.head;
this.head = first;
this.size++;
}
#SuppressWarnings({"unchecked"})
public boolean equals(Object o) {
// TODO
return false; // if we reach this, everything matched successfully
}
#SuppressWarnings({"unchecked"})
public SinglyLinkedList<E> clone() throws CloneNotSupportedException {
// TODO
return null;
}
/**
* Produces a string representation of the contents of the list.
* This exists for debugging purposes only.
* #return
*/
public String toString() {
for(int i=0;i<this.size();i++) {
System.out.println(this.get(i));
}
return "end of Linked List";
}
public static void main(String[] args) {
SinglyLinkedList <Integer> ll =new SinglyLinkedList <Integer>();
ll.addFirst(5);
ll.addFirst(4);
ll.addFirst(3);
ll.addFirst(2);
ll.set(1,0);
System.out.println(ll);
}
}
Assumptions
addLast method is missing in the code
The error could be there too
Known cause
This code is not incrementing the size inside the set method's for loop.The size is incremented in addLast(possibly) and addFirst and not incremented in other case (final else part)
It is not clear what is planned to do with set method. The way it is implemented now, it behaves more like insert, meaning that it will add new node, bit it does not increase the total count of elements (size).
It the set method is changing the value of the node, which name indicates, then this part is wrong:
else {
for(int j=0; current != null && j < (i-1);j++) {
current = current.next;
}
Node<E> temp = current.next;
current.next = setNode;
setNode.next = temp;
}
It should replace the value instead of adding the new one:
else {
for(int j=0; current != null && j < (i-1);j++) {
current = current.next;
}
current.value=e
}
Also, it looks like the index i is 1-based, while everything else is 0 based. I didn't check the code above, but the concept should be like shown.
So I built myself a trie data structure in java but instead of arrays containing LinkedLists to each node's children. But I am having some problems. The first word gets added just fine, but on the second word, it is always comparing the wrong prefixes. For example, I start off by adding "at". This works. Then I add "Hello" and this is the result:
adding 'at'
CURRENT CHAR IS: a
List is empty, can't iterate
List is empty, can't iterate
Can't find this char, adding node...
Returning child
CURRENT CHAR IS: t
List is empty, can't iterate
List is empty, can't iterate
Can't find this char, adding node...
END OF LINE; SET IT TO TRUE--------------
Returning child
adding 'Hello'
CURRENT CHAR IS: H
List is NOT empty
char H lista a?
false
List is empty, can't iterate
List is NOT empty
char H lista a?
false
List is empty, can't iterate
Can't find this char, adding node...
Returning child
CURRENT CHAR IS: e
List is NOT empty
char e lista at?
false
List is empty, can't iterate
List is NOT empty
char e lista at?
false
List is empty, can't iterate
Can't find this char, adding node...
Returning child
CURRENT CHAR IS: l
List is empty, can't iterate
List is empty, can't iterate
Can't find this char, adding node...
Returning child
CURRENT CHAR IS: l
List is empty, can't iterate
List is empty, can't iterate
Can't find this char, adding node...
Returning child
CURRENT CHAR IS: o
List is empty, can't iterate
List is empty, can't iterate
Can't find this char, adding node...
END OF LINE; SET IT TO TRUE--------------
Here is my code(sorry for all the prints and comments, have been debugging for a couple of hours)
Trie
public class Trie {
private Node root;
private int size;
/**
* Creates the root node and sets the size to 0.
*/
public Trie() {
root = new Node();
size = 0;
}
/**
* Adds a new word to the trie.
*
* #param word
* #return
*/
//vi lägger in "Hello"
public boolean add(String word) {
System.out.println("adding " + word);
Node curr = root;
if (curr == null || word == null) {
return false;
}
int i = 0;
char[] chars = word.toCharArray();
// Loop through all letters in the word.
while (i < chars.length) {
System.out.println("lengt = " + chars.length);
LinkedList<Node> children = curr.getChildren();
// If the children nodes does not contain the letter at i.
System.out.println("BEFORE CURRENT CHAR IS: " + chars[i]);
if (!childContain(children, String.valueOf(chars[i]))) {//TODO? listan är tom.
// Insert a new node
insertNode(curr, chars[i]);
System.out.println("Can't find this word, adding...");
// if we have traversed all letters.
if (i == chars.length - 1) {
System.out.println("END OF LINE; SET IT TO TRUE--------------");
// Get the child and set word to true ie we have found it.
getChild(curr, chars[i]).setWord(true);
size++;
return true;
}
}
// get the current child.
curr = getChild(curr, chars[i]); //NOT SURE ABOUT THIS!
// If the current childs text is equal the word or not the word.
if (curr.getText().equals(word) && !curr.isWord()) {
// set the current word to true.
curr.setWord(true);
size++;
return true;
}
i++;
}
return false;
}
/**
* Returns true if the given string is found.
* TODO: FIX!
* #param str
* #return
*/
public boolean find(String str) {
System.out.println(str);
System.out.println("-----------------------------------------");
LinkedList<Node> children = root.getChildren();
Node node = null;
char[] chars = str.toCharArray();
//Loop over all letters.
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
//If child contains c.
if (childContain(children, String.valueOf(c))) {
System.out.println("DET FINNS");
//get the child and it's children.
node = getChild(root, c);
children = node.getChildren();
} else {
System.out.println("DET FINNS INGET");
return false;
}
}
return true;
}
/**
* Inserts a new Node with a char.
*
* #param node
* #param c
* #return
*/
private Node insertNode(Node node, Character c) {
if (childContain(node.getChildren(), String.valueOf(c))) {
return null;
}
Node next = new Node(node.getText() + c.toString());
node.getChildren().add(next);
return next;
}
/**
* Retrieves a given node's child with the character c
*
* #param trie
* #param c
* #return
*/
private Node getChild(Node node, Character c) {
LinkedList<Node> list = node.getChildren();
Iterator<Node> iter = list.iterator();
while (iter.hasNext()) {
Node n = iter.next();
if (n.getText().equals(String.valueOf(c)));
{
System.out.println("Returning child");
return n;
}
}
System.out.println("Returning null"); // This could never happen
return null;
}
/**
* Checks if any child contains the char c.
*
* #param list
* #param c
* #return
*/
private boolean childContain(LinkedList<Node> list, String c) {
Iterator<Node> iter = list.iterator();
while (iter.hasNext()) {
System.out.println("List is NOT empty");
Node n = iter.next();
//GÖr en substräng av den existerande noden
System.out.println("char " + (c) +" lista " + n.getText() + "?");
System.out.println(n.getText().equals(c));
if (n.getText().equals(c))
{
return true;
}
}
System.out.println("List is empty, can't iterate");
return false;
}
/**
* Returns the trie's size.
*
* #return
*/
public int getSize() {
return size;
}
}
Node:
public class Node {
private boolean isWord;
private String text;
private LinkedList<Node> children;
public Node() {
children = new LinkedList<Node>();
text = "";
isWord = false;
}
public Node(String text) {
this();
this.text = text;
}
public LinkedList<Node> getChildren(){
return children;
}
public boolean isWord() {
return isWord;
}
public void setWord(boolean isWord) {
this.isWord = isWord;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
#Override
public String toString(){
return text;
}
}
I found 3 bugs.
Frist, this getChild() method has misplaced semicolon that is causing your method to return at the first node:
if (n.getText().equals(String.valueOf(c)))/*; - remove this semicolon*/
{
System.out.println("Returning child");
return n;
}
Second, I'm assuming you want each node in your trie to only contain a single letter. Therefore, you must correct the insertNode() method like so:
Node next = new Node(/*node.getText() + - remove this*/c.toString());
If you run that code, you will get a NullPointerException trying to find words that you add. This is because in your find method has a few bugs. I rewrote it and added some comments that explain the changes. Please let me know if it's unclear:
public boolean find(String str) {
LinkedList<Node> children = root.getChildren();
// start the node at the root
Node node = root;
char[] chars = str.toCharArray();
//Loop over all letters.
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
//If child contains c.
if (childContain(children, String.valueOf(c))) {
//get the child *of the node, not root* and it's children.
node = getChild(node, c);
// there are better ways to handle this, but I think this explicitly shows what the situations is
if (node == null) {
// we have reached a node that does not have children
if (i == chars.length - 1) {
// we are at the end of the word - it is found
return true;
} else {
// we are in the middle of the word - it is not present
return false;
}
}
// if we have reached the end of the word this will cause NullPointer
children = node.getChildren();
} else {
return false;
}
}
return true;
}
When I run this snippet:
public static void main(String[] args) {
Trie trie = new Trie();
trie.add("at");
trie.add("Hello");
System.out.println(trie.find("at"));
System.out.println(trie.find("Hello"));
System.out.println(trie.find("yea"));
}
I get "true", "true", "false"
Having Trouble with the method getFrequencyOf(aData), returns zero for every element I am searching for in the Test code...here's my code if anyone can point me to what I'm doing wrong that would be much appreciated
public class FrequencyBag<T>
{
// TO DO: Instance Variables
private Node firstNode;
private int numberOfEntries;
/**
* Constructor
* Constructs an empty frequency bag.
*/
public FrequencyBag()
{
// TO DO
firstNode = null;
numberOfEntries = 0;
}
/**
* Adds new entry into this frequency bag.
* #param aData the data to be added into this frequency bag.
*/
public void add(T aData)
{
// TO DO
if(numberOfEntries != 0){
Node newNode = new Node(aData);
newNode.next = firstNode.next;
firstNode = newNode;
numberOfEntries++;
}
else{
Node newNode = new Node(aData);
firstNode = newNode;
}
}
/**
* Gets the number of occurrences of aData in this frequency bag.
* #param aData the data to be checked for its number of occurrences.
* #return the number of occurrences of aData in this frequency bag.
*/
public int getFrequencyOf(T aData)
{
// TO DO
int counter = 0;
Node currentNode = firstNode;
for(int i = 1; i <= numberOfEntries; i++)
{
if(currentNode.data.equals(aData))
{
counter++;
System.out.println(counter);
}
currentNode = currentNode.next;
}
System.out.println(counter);
return counter;
}
/**
* Gets the maximum number of occurrences in this frequency bag.
* #return the maximum number of occurrences of an entry in this
* frequency bag.
*/
public int getMaxFrequency()
{
// TO DO
Node currentNode = firstNode;
int currentFrequency = 0;
int maxFrequency = currentFrequency;
for(int i = 1; i <= numberOfEntries; i++)
{
currentFrequency = getFrequencyOf(currentNode.data);
if(currentFrequency > maxFrequency)
{
maxFrequency = currentFrequency;
}
currentNode = currentNode.next;
}
return maxFrequency;
}
/**
* Gets the probability of aData
* #param aData the specific data to get its probability.
* #return the probability of aData
*/
public double getProbabilityOf(T aData)
{
// TO DO
int num = getFrequencyOf(aData);
double probability = num / numberOfEntries;
return probability;
}
/**
* Empty this bag.
*/
public void clear()
{
// TO DO
firstNode.next = null;
firstNode.data = null;
}
/**
* Gets the number of entries in this bag.
* #return the number of entries in this bag.
*/
public int size()
{
// TO DO
return numberOfEntries;
}
private class Node
{
private T data;
private Node next;
public Node (T a)
{
data = a;
next = null;
}
public Node(T a, Node n)
{
data = a;
next = n;
}
}
}
To be honest, I did not read the full code, because there is a mistake in the add method, which probably causes the problem you face:
Node newNode = new Node(aData);
newNode.next = firstNode.next; //firstNode.next is null!
firstNode = newNode;
When you add the first node, it's pointing to a null node (its next value is null).
Then, when you add a second node, as in the line above, your new head of the list points to the next node of the previous head, which is always null. So, your list always has only one node, the firstNode. To fix that, change the above lines as:
Node newNode = new Node(aData);
newNode.next = firstNode;
firstNode = newNode;
OR (using the second constructor):
Node newNode = new Node(aData,firstNode);
firstNode = newNode;
This will make your new node the head of the linked list, having as its next element the previous head of the list.
UPDATE:
Also, another problem is that numberOfEntries is always 0, since you do not increment it when you add the very first node. So, add a numberOfEntries++; inside the else block of the add() method, or just move the one that exists in the if block, outside the block.
I've created a CircularLinkedList class, instead of using the util LinkedList class. The problem is based off of the Josephus problem, stating that for a circle of 20 people, each 12th person is to be killed until it is determined which position the survivor will be left standing in (using an Iterator). I'm confused as to how I could use an Iterator with this problem, since I'm using my own class instead of LinkedList, which already has an iterator() method so that I could declare an Iterator like this:
Iterator<E> iter = cll.iterator();
I have no idea how I would write my own Iterator method, and I feel like I have to be over thinking this. Any help is appreciated! I can post my code if it would clear anything up that I forgot to mention
I'm still stuck on this, so I figured I'd post my code to see if anyone can help. It's a lot, so I apologize.
Itr class (Iterator)
import java.util.Iterator;
public class Itr<E> extends CircularLinkedList<E> implements Iterator<E>
{
/** the size of the list */
private int size = 0;
/** for the hasNext() method for Iterator */
private int nextNode = 0;
/** two Nodes used for next() method for Iterator */
private Node<E> lastReturned = null;
private Node<E> nextUp;
/** part of the Iterator implementation */
public boolean hasNext()
{
return nextNode < size;
}
/** part of the Iterator implementation */
public E next()
{
lastReturned = nextUp;
nextUp = nextUp.getNext();
nextNode++;
return lastReturned.data;
}
/** part of the Iterator implementation */
public void remove()
{
Node<E> lastNext = lastReturned.getNext();
if (lastReturned == null)
nextUp = lastNext;
else
nextNode--;
lastReturned = null;
}
}
Josephus class
public class Josephus<E>
{
public static void main(String[] args)
{
CircularLinkedList cll = new CircularLinkedList();
Itr iter = cll.iterator();
int lastMan = 0;
int n = 20;
int passes = 12;
while(n > 1)
{
iter.next();
for(int i = 0; i < n; i += passes)
{
iter.hasNext();
iter.remove();
if(n == 1)
lastMan = n;
}
}
System.out.println("Survior: " + lastMan);
}
}
CircularLinkedList class
public class CircularLinkedList<E>
{
public class Node<E>
{
/* data value **/
public E data;
/* the link **/
private Node<E> next = null;
/** constructs a Node with given data and link
* #param data the data value
* #param next the link
*/
public Node(E data, Node<E> next)
{
this.data = data;
this.next = next;
}
/** construct a Node with given data value
* #param data the data value
*/
public Node(E data)
{
this.data = data;
}
/** return the data value of a Node
* #return the data value
*/
public E getData()
{
return data;
}
/** set the next Node in a list
* #param append the data value that the new Node will contain
*/
public void setNext(Node append)
{
next = append;
}
/** return the next Node
* # return the next Node
*/
public Node<E> getNext()
{
if(current.next == null)
current.next = current;
return next;
}
}
/** a reference into the list */
private Node<E> current = null;
/** the size of the list */
private int size = 0;
/** helper methods */
/** remove the first occurance of element item.
* #param item the item to be removed
* #return true if item is found and removed; otherwise, return false.
*/
public void removeItem(E item)
{
Node<E> position = current;
Node<E> nextPosition1,
nextPosition2;
while (position.next != null)
{
if(position.getNext().getData().equals(item))
{
nextPosition1 = position.getNext();
nextPosition2 = nextPosition1.getNext();
position.setNext(nextPosition2);
}
else
{
position = position.getNext();
}
}
}
/** set the first Node in a list
* #param append the data value that the new Node will contain
*/
public void addFirst(E append)
{
current = new Node<E>(append, current);
size++;
}
/** add a new Node as the last in the List
* #param data value of the new Node
*/
public void addNext(E value)
{
// location for new value
Node<E> temp = new Node<E>(value,null);
if (current != null)
{
// pointer to possible tail
Node<E> finger = current;
while (finger.next != null)
{
finger = finger.next;
}
finger.setNext(temp);
} else current = temp;
size++;
}
/** return the data value of the fourth Node in the list
* #return the data value
*/
public E printFourth()
{
current.next.next.next = current;
return current.next.next.next.getData();
}
/** return the size of the LinkedList
* #return the size
*/
public int size()
{
return size;
}
public E get(int index)
{
Node<E> temp = null;
for(int i = 0; i < index; i++)
{
temp = current.next;
System.out.print(temp.getData() + " ");
}
return temp.getData();
}
public Itr<E> iterator()
{
return new Itr<E>();
}
#Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("[");
Node<E> aux = this.current;
boolean isFirst = true;
while(aux != null)
{
if(!isFirst)
{
sb.append(", ");
}
isFirst = false;
sb.append(aux.data.toString());
aux=aux.next;
}
return sb.append("]").toString();
}
}
I'm getting a NullPointerException from the next() method in the Itr class on the line
nextUp = nextUp.getNext();
Am I doing something wrong in the CircularLinkedList class for it to not actually be circular or is there a problem with my driver/Itr classes? I'm kind of lost at this point. Any help is appreciated.
Create a custom class which implements Iterator and return the custom Iterator from your CLL.iterator method.
See LinkedList#ListItr for inspiration - but only conside the Iterator methods (next, hasNext, remove) for this exercise. A true circular linked-list will simply follow the next node, always, and has no end - hasNext will always return true if there is at least one element. If your CLL implementation has an "end", then make sure to "move back to the start" when it is encountered.
In addition, the CLL class should conform to Iterable, which means it has an iterator method to obtain an Iterator.
I want to initialize an Item Array but can't figure it out.
Here is my code.
public class HashTable<Item> {
private int m; // hash table size
private Item[] T; // hash table
HashTable(int M)
{
m = M;
T = new Item[M];
for(int i=0;i<M;i++){
Item T[i] = null;
}
}
...
...
SOLUTION
T = (Item[])new Object[M];
I think what you need is something like:
for(int i=0;i<M;i++){
T[i] = new Item(); // call some constructor here
}
You have
Item T[i] = ...
in your loop, while it should be just
T[i] = ...
So try these hints.
Also do this:
T = (Item[])new Object[M];
as Kumar suggested in his reply.
The thing is that Item is not really a type here. You need
to read how generics are actually compiled into bytecode,
and you will see what happens under the hood.
You are trying to create the array of Generic type,Please look at this post.
How to create a generic array in Java?
Assuming you created the class item you could call it like this:
public class HashTable
{
private int tableSize; // hash table size
private Item[] table; // hash table
public static void main(String[] args)
{
// where 10 is the number of nodes
Item[] myTable = createHashTable(10);
}
private static Item[] createHashTable(int size)
{
Item[] table = new Item[size];
for(int i = 0; i < table.length; i++)
{
table[i] = new Item(i);
}
}
}
However if you want to see an example of a full HashTable implementation:
/*
* HashTable.java
*
*
*/
/**
* A class that implements a hash table that employs open addressing
* using either linear probing, quadratic probing, or double hashing.
*/
public class HashTable {
/* Private inner class for an entry in the hash table */
private class Entry {
private String key;
private LLList valueList; // all of the values with this key
private boolean hasBeenRemoved; // has this entry been removed?
private Entry(String key, int value) {
this.key = key;
valueList = new LLList();
valueList.addItem(value, 0);
hasBeenRemoved = false;
}
}
// parameters for the second hash function -- see h2() below
private static final int H2_MIN = 5;
private static final int H2_DIVISOR = 11;
// possible types of probing
public static final int LINEAR = 0;
public static final int QUADRATIC = 1;
public static final int DOUBLE_HASHING = 2;
public static final int NUM_PROBE_TYPES = 3;
private Entry[] table; // the hash table itself
private int probeType = LINEAR; // the type of probing
// keeps track of how many times we perform a probe of a given length
private int[] probeLengthCount;
public HashTable(int size, int probeType) {
if (probeType >= 0 && probeType < NUM_PROBE_TYPES)
this.probeType = probeType;
else
throw new IllegalArgumentException("invalid probeType: " +
probeType);
table = new Entry[size];
probeLengthCount = new int[size + 1];
for (int i = 0; i <= size; i++)
probeLengthCount[i] = 0;
}
public HashTable(int size) {
// Call the other constructor to do the work.
this(size, LINEAR);
}
/* first hash function */
private int h1(String key) {
int h1 = key.hashCode() % table.length;
if (h1 < 0)
h1 += table.length;
return h1;
}
/* second hash function */
private int h2(String key) {
int h2 = key.hashCode() % H2_DIVISOR;
if (h2 < 0)
h2 += H2_DIVISOR;
h2 += H2_MIN;
return h2;
}
/*
* probeIncrement - returns the amount by which the current index
* should be incremented to obtain the nth element in the probe
* sequence
*/
private int probeIncrement(int n, int h2) {
if (n <= 0)
return 0;
switch (probeType) {
case LINEAR:
return 1;
case QUADRATIC:
return (2*n - 1);
case DOUBLE_HASHING:
default:
return h2;
}
}
/*
* probe - attempt to find a slot in the hash table for the specified key.
*
* If key is currently in the table, it returns the index of the entry.
* If key isn't in the table, it returns the index of the first empty cell
* in the table.
* If overflow occurs, it returns -1.
*/
private int probe(String key) {
int i = h1(key); // first hash function
int h2 = h2(key); // second hash function
int positionsChecked = 1;
// keep probing until we get an empty position or a match
while (table[i] != null && !key.equals(table[i].key)) {
if (positionsChecked == table.length) {
probeLengthCount[positionsChecked]++;
return -1;
}
i = (i + probeIncrement(positionsChecked, h2)) % table.length;
positionsChecked++;
}
probeLengthCount[positionsChecked]++;
return i;
}
/**
* insert - insert the specified (key, value) pair in the hash table
*/
public void insert(String key, int value) {
if (key == null)
throw new IllegalArgumentException("key must be non-null");
int i = h1(key);
int h2 = h2(key);
int positionsChecked = 1;
int firstRemoved = -1;
while (table[i] != null && !key.equals(table[i].key)) {
if (table[i].hasBeenRemoved && firstRemoved == -1)
firstRemoved = i;
if (positionsChecked == table.length)
break;
i = (i + probeIncrement(positionsChecked, h2)) % table.length;
positionsChecked++;
}
probeLengthCount[positionsChecked]++;
if (table[i] != null && key.equals(table[i].key))
table[i].valueList.addItem(value, 0);
else if (firstRemoved != -1)
table[firstRemoved] = new Entry(key, value);
else if (table[i] == null)
table[i] = new Entry(key, value);
else
throw new RuntimeException("overflow occurred");
}
/**
* search - search for the specified key, and return the
* associated list of values, or null if the key is not in the
* table
*/
public LLList search(String key) {
if (key == null)
throw new IllegalArgumentException("key must be non-null");
int i = probe(key);
if (i == -1 || table[i] == null)
return null;
else
return table[i].valueList;
}
/**
* remove - remove from the table the entry for the specified key
*/
public void remove(String key) {
if (key == null)
throw new IllegalArgumentException("key must be non-null");
int i = probe(key);
if (i == -1 || table[i] == null)
return;
table[i].key = null;
table[i].valueList = null;
table[i].hasBeenRemoved = true;
}
/**
* printStats - print the statistics for the table -- i.e., the
* number of keys and items, and stats for the number of times
* that probes of different lengths were performed
*/
public void printStats() {
int numProbes = 0;
int probeLengthSum = 0;
int numKeys = 0;
for (int i = 0; i < table.length; i++) {
if (table[i] != null && !table[i].hasBeenRemoved)
numKeys++;
}
System.out.println("\n" + numKeys + " keys");
System.out.println("probe-length stats:");
System.out.println("length\tcount");
for (int i = 1; i <= table.length; i++) {
if (probeLengthCount[i] != 0)
System.out.println(i + "\t" + probeLengthCount[i]);
numProbes += probeLengthCount[i];
probeLengthSum += (probeLengthCount[i] * i);
}
System.out.println("average probe length = " +
(double)probeLengthSum / numProbes);
}
}
Here is the second file for a Linked-Linked-List
/*
* LLList.java
*
*
*/
import java.util.*;
/**
* A class that implements our simple List interface using a linked list.
* The linked list includes a dummy head node that allows us to avoid
* special cases for insertion and deletion at the front of the list.
*/
public class LLList implements List {
// Inner class for a node. We use an inner class so that the LLList
// methods can access the instance variables of the nodes.
private class Node {
private Object item;
private Node next;
private Node(Object i, Node n) {
item = i;
next = n;
}
}
private Node head; // dummy head node
private int length; // # of items in the list
/**
* Constructs a LLList object for a list that is initially empty.
*/
public LLList() {
head = new Node(null, null);
length = 0;
}
/*
* getNode - private helper method that returns a reference to the
* ith node in the linked list. It assumes that the value of the
* parameter is valid.
*
* If i == -1, it returns a reference to the dummy head node.
*/
private Node getNode(int i) {
Node trav = head;
int travIndex = -1;
while (travIndex < i) {
travIndex++;
trav = trav.next;
}
return trav;
}
/** getItem - returns the item at position i in the list */
public Object getItem(int i) {
if (i < 0 || i >= length)
throw new IndexOutOfBoundsException();
Node n = getNode(i);
return n.item;
}
/**
* addItem - adds the specified item at position i in the list,
* shifting the items that are currently in positions i, i+1, i+2,
* etc. to the right by one. Always returns true, because the list
* is never full.
*
* We don't need a special case for insertion at the front of the
* list (i == 0), because getNode(0 - 1) will return the dummy
* head node, and the rest of insertion can proceed as usual.
*/
public boolean addItem(Object item, int i) {
if (i < 0 || i > length)
throw new IndexOutOfBoundsException();
Node newNode = new Node(item, null);
Node prevNode = getNode(i - 1);
newNode.next = prevNode.next;
prevNode.next = newNode;
length++;
return true;
}
/**
* removeItem - removes the item at position i in the list,
* shifting the items that are currently in positions i+1, i+2,
* etc. to the left by one. Returns a reference to the removed
* object.
*
* Here again, we don't need a special case for i == 0 (see the
* note accompanying addItem above).
*/
public Object removeItem(int i) {
if (i < 0 || i >= length)
throw new IndexOutOfBoundsException();
Node prevNode = getNode(i - 1);
Object removed = prevNode.next.item;
prevNode.next = prevNode.next.next;
length--;
return removed;
}
/** length - returns the number of items in the list */
public int length() {
return length;
}
/**
* isFull - always returns false, because the linked list can
* grow indefinitely and thus the list is never full.
*/
public boolean isFull() {
return false;
}
/**
* toString - converts the list into a String of the form
* [ item0 item1 ... ]
*/
public String toString() {
String str = "[ ";
Node trav = head.next; // skip over the dummy head node
while (trav != null) {
str += (trav.item + " ");
trav = trav.next;
}
str += "]";
return str;
}
/**
* iterator - returns an iterator for this list
*/
public ListIterator iterator() {
return new LLListIterator();
}
/*
*** private inner class for an iterator over an LLList ***
*/
private class LLListIterator implements ListIterator {
private Node nextNode; // the next node to visit
private Node lastVisitedNode; // the most recently visited node
public LLListIterator() {
nextNode = head.next;
lastVisitedNode = null;
}
/**
* hasNext - does the iterator have additional items to visit?
*/
public boolean hasNext() {
return (nextNode != null);
}
/**
* next - returns a reference to the next Object in the iteration
*/
public Object next() {
if (nextNode == null)
throw new NoSuchElementException();
Object item = nextNode.item;
lastVisitedNode = nextNode;
nextNode = nextNode.next;
return item;
}
}
}