-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTableChaining.java
More file actions
104 lines (96 loc) · 2.63 KB
/
HashTableChaining.java
File metadata and controls
104 lines (96 loc) · 2.63 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import java.util.Scanner;
import java.util.LinkedList;
class CWOR
{
LinkedList<Integer>[] table;
int size;
CWOR(int size)
{
this.size=size;
table=new LinkedList[size];
for(int i=0;i<size;i++)
{
table[i]=new LinkedList<>();
}
}
public void insert(int key)
{
int idx=hashfun(key);
table[idx].add(key);
}
private int hashfun(int key)
{
return key%size;
}
public void display()
{
System.out.println("Hash Table:");
for(int j=0;j<size;j++)
{
System.out.print("Index "+j+": ");
for(int key:table[j])
{
System.out.print(key+" -> ");
}
System.out.println("null");
}
}
public void search(int key)
{
int idx=hashfun(key);
if(table[idx].contains(key))
{
System.out.println("Element " + key + " found at index: " + idx);
}
else
{
System.out.println("Element " + key + " not found!");
}
}
}
class HashTableChaining
{
public static void main(String[] args)
{
Scanner sr=new Scanner(System.in);
System.out.print("Enter table size: ");
int size=sr.nextInt();
if(size <= 0)
{
System.out.println("Invalid table size. Exiting.");
return;
}
CWOR c=new CWOR(size);
while(true)
{
System.out.println("Menu: \n1. Insert \n2. Display \n3. Search \n4. Exit");
System.out.print("Enter Choice: ");
int ch=sr.nextInt();
switch(ch)
{
case 1:
System.out.print("How many elements do you want to insert: ");
int n=sr.nextInt();
System.out.print("Enter elements: ");
for(int i=0;i<n;i++)
{
c.insert(sr.nextInt());
}
break;
case 2:
c.display();
break;
case 3:
System.out.print("Enter the element you want to search: ");
c.search(sr.nextInt());
break;
case 4:
System.out.println("Program Ended!");
sr.close();
return;
default:
System.out.println("Invalid choice!");
}
}
}
}