-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyHashTable.java
More file actions
86 lines (85 loc) · 1.92 KB
/
MyHashTable.java
File metadata and controls
86 lines (85 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
public class MyHashTable
{
public MyLinkedList<WordEntry>[] mht=new MyLinkedList[676];
public MyHashTable()
{
for (int i=0;i<676;i++)
{
mht[i]=new MyLinkedList<WordEntry>();
}
}
private int getHashIndex(String str)
{
int i;
if(str.length()>1)
{
i=(((str.charAt(0))-97)*26)+(str.charAt(1)-97);
if (i<0)
{
i=i*(-1);
}
return (i%676);
}
else
{
i=str.charAt(0);
return (i%676);
}
}
void addPositionsForWord(WordEntry w)
{
int hashIndexForWord=getHashIndex(w.str);
if(mht[hashIndexForWord]!=null){
if(!mht[hashIndexForWord].isEmpty())
{
Node<WordEntry> temp = mht[hashIndexForWord].header.getNext();
while (temp.next!=null)
{
if (temp.getElement().str.equals(w.str))
{
temp.getElement().addPositions(w.getAllPositionsForThisWord());
break;
}
temp = temp.getNext();
}
if (temp.getNext()==null)
{
WordEntry wn=new WordEntry(w.str);
wn.addPositions(w.getAllPositionsForThisWord());
Node<WordEntry> ne=new Node<WordEntry>(wn,null,null);
mht[hashIndexForWord].addLast(ne);
}
}
else
{
WordEntry wn=new WordEntry(w.str);
wn.addPositions(w.getAllPositionsForThisWord());
Node<WordEntry> ne=new Node<WordEntry>(wn,null,null);
mht[hashIndexForWord].addLast(ne);
}
}
else
{
MyLinkedList<WordEntry> newll = new MyLinkedList<>();
mht[hashIndexForWord]=newll;
WordEntry wn=new WordEntry(w.str);
wn.addPositions(w.getAllPositionsForThisWord());
Node<WordEntry> ne=new Node<WordEntry>(wn,null,null);
mht[hashIndexForWord].addLast(ne);
}
}
public WordEntry getWord(String s)
{
int i=getHashIndex(s);
Node<WordEntry> f=mht[i].header.getNext();
for (int j=0;j<mht[i].size();j++)
{
if (s.equals(f.getElement().str))
{
return f.getElement();
}
f=f.getNext();
}
return null;
}
}