Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package histogram_words;
- class ListNode {
- String word;
- int occurences;
- ListNode next;
- public ListNode(String w, int o, ListNode n) {
- word=w; occurences=o; next=n;
- }
- }
- public class MyHashTable {
- ListNode buckets[];
- int length;
- public MyHashTable(int size) {
- buckets=new ListNode[size];
- }
- public void add(String word, int occurences) {
- int index=myHash(word);
- ListNode ptr=buckets[index];
- while (ptr!=null) {
- if (ptr.word.equals(word)) {
- ptr.occurences = occurences;
- return;
- }
- ptr=ptr.next;
- }
- ListNode newNode=new ListNode(word, 1, buckets[index]);
- buckets[index]=newNode;
- }
- public int myHash(String word) {
- int index=word.hashCode() % buckets.length;
- if (index<0) return -index;
- else return index;
- }
- public int get(String word) {
- int index=myHash(word);
- ListNode ptr=buckets[index];
- while (ptr!=null) {
- if (ptr.word.equals(word)) {
- return ptr.occurences;
- }
- ptr=ptr.next;
- }
- return 0;
- }
- public String toString() {
- String result="";
- for (int i=0; i<buckets.length; i++) {
- ListNode ptr=buckets[i];
- while (ptr!=null) {
- result += ptr.word +": "+ptr.occurences+"\n";
- ptr=ptr.next;
- }
- }
- return result;
- }
- }
RAW Paste Data