-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathHashTableDoublyLinkedLists.java
123 lines (102 loc) · 3.08 KB
/
HashTableDoublyLinkedLists.java
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
class DoublyLinkedListNode{
DoublyLinkedListNode next, prev;
int data;
DoublyLinkedListNode(int data){
this.data = data;
next = null;
prev = null;
}
}
public class HashTableDoublyLinkedLists {
DoublyLinkedListNode[] hashtable;
int size;
HashTableDoublyLinkedLists(int hashtablesize) {
hashtable = new DoublyLinkedListNode[hashtablesize];
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public void clear(){
int len = hashtable.length;
hashtable = new DoublyLinkedListNode[len];
size = 0;
}
public int getSize() {
return size;
}
public void insert(int value) {
size++;
int position = hash(value);
DoublyLinkedListNode node = new DoublyLinkedListNode(value);
DoublyLinkedListNode start = hashtable[position];
if (hashtable[position] == null)
hashtable[position] = node;
else {
node.next = start;
start.prev = node;
hashtable[position] = node;
}
}
public void remove(int value) {
try {
int position = hash(value);
DoublyLinkedListNode start = hashtable[position];
DoublyLinkedListNode end = start;
if (start.data == value) {
size--;
if (start.next == null) {
// removing the value
hashtable[position] = null;
return;
}
start = start.next;
start.prev = null;
hashtable[position] = start;
return;
}
while (end.next != null
&& end.next.data != value)
end = end.next;
if (end.next == null) {
System.out.println("\nElement not found\n");
return;
}
size--;
if (end.next.next == null) {
end.next = null;
return;
}
end.next.next.prev = end;
end.next = end.next.next;
hashtable[position] = start;
} catch (Exception e) {
System.out.println("\nElement not found\n");
}
}
private int hash(Integer x) {
int hashValue = x.hashCode();
hashValue %= hashtable.length;
if (hashValue < 0)
hashValue += hashtable.length;
return hashValue;
}
public void printHashTable() {
System.out.println();
for (int i = 0; i < hashtable.length; i++) {
System.out.print("At " + i + ": ");
DoublyLinkedListNode start = hashtable[i];
while (start != null) {
System.out.print(start.data + " ");
start = start.next;
}
System.out.println();
}
}
public static void main(String[] args) {
HashTableDoublyLinkedLists ht = new HashTableDoublyLinkedLists(5);
ht.insert(1);
ht.insert(2);
ht.printHashTable();
}
}