The Wayback Machine - https://web.archive.org/web/20240725081714/https://www.geeksforgeeks.org/java-program-to-implement-hash-tables-chaining-with-doubly-linked-lists/
Open In App

Java Program to Implement Hash Tables Chaining with Doubly Linked Lists

Last Updated : 19 Jan, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Hash Tables(similar to tables in general) provide a subset of the dynamic set operations. Usually, a set of keys are mapped with some values based on certain relations. However, there might be situations when different keys map to the same position provided by the Hash function, which leads to a collision.

One of the ways to overcome this situation is Hash Table Chaining. 

The chaining approach to resolve collisions deals with it by going ahead and putting all the keys that map to a slot in that slot but representing them as a linked list.

Hash Table chaining in Java is possible with both, Singly Linked List and Doubly Linked List. Though the implementation is same, the only difference is that Doubly Linked List allows two-way traversal i.e., the node contains a pointer to the next as well as the previous node. Thus, the complexity of insertion and deletion at a known position reduces to O(1) as compared to the Singly Linked List (O(n)).

Example :

In Singly Linked List : g -> e -> e -> k -> s
Here, each node contains a pointer to the next node only.

In Doubly Linked List : g <-> e <-> e <-> k <-> s
Each node contains pointer to the next as well as previous node.

Approach :

  1. Insertion: To insert, a key is simply hashed to get the position in the table (the list where this new key has to be inserted), and then insert the key at the head of the doubly linked list using the standard linked list procedures (given in the code).
  2. Deletion: Just go through the list that the key maps to through the hash function and delete the key from that list using the standard linked list procedures (given in the code).

Below is the implementation of the above approach:

Java




// Java implementation of Hashtable chaining
// using doubly linked list
  
import java.util.*;
  
class DoublyLinkedListNode {
    // Declaration of Nodes
    DoublyLinkedListNode next, prev;
    int data;
  
    // constructor
    DoublyLinkedListNode(int data)
    {
        this.data = data;
        next = null;
        prev = null;
    }
}
class HashTableChainingDoublyLinkedList {
    // Declaration of Hash Table
    DoublyLinkedListNode[] hashTable;
  
    // stores the size of HashTable
    int size;
  
    // Constructor
    HashTableChainingDoublyLinkedList(int hashTableSize)
    {
        // Creating an empty Hash Table
        hashTable = new DoublyLinkedListNode[hashTableSize];
        size = 0;
    }
  
    // Function to check if hash table is empty
    public boolean isEmpty() { return size == 0; }
  
    // Function to clear/delete all elements from Hash table
    public void clear()
    {
        // Capacity of Hash Table
        int len = hashTable.length;
  
        // Creating new empty Hash Table
        // of same initial capacity
        hashTable = new DoublyLinkedListNode[len];
        size = 0;
    }
  
    // Function that returns size of Hash Table
    public int getSize() { return size; }
  
    // Function to insert a value/element
    public void insert(int value)
    {
        size++;
  
        // gets the position/index where the value should be
        // stored
        int position = hash(value);
  
        // creates a node for storing 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;
        }
    }
  
    // Function to remove an element
    public void remove(int value)
    {
        try {
            // gets the position where the value to
            // be deleted exists
            int position = hash(value);
  
            DoublyLinkedListNode start
                = hashTable[position];
  
            DoublyLinkedListNode end = start;
  
            // if value is found at 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;
            }
  
            // traversing the list
            // until the value is found
            while (end.next != null
                   && end.next.data != value)
                end = end.next;
  
            // if reached at the end without finding the
            // value
            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");
        }
    }
  
    // Definition of Hash function
    private int hash(Integer x)
    {
        int hashValue = x.hashCode();
  
        hashValue %= hashTable.length;
  
        if (hashValue < 0)
            hashValue += hashTable.length;
  
        return hashValue;
    }
  
    // Function to print hash table
    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();
        }
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        HashTableChainingDoublyLinkedList hashTab
            = new HashTableChainingDoublyLinkedList(5);
  
        hashTab.insert(99);
        hashTab.insert(23);
        hashTab.insert(36);
        hashTab.insert(47);
        hashTab.insert(80);
  
        hashTab.printHashTable();
  
        hashTab.insert(92);
        hashTab.insert(49);
  
        hashTab.printHashTable();
  
        hashTab.remove(99);
  
        hashTab.printHashTable();
  
        hashTab.clear();
  
        hashTab.printHashTable();
  
        System.out.println(hashTab.isEmpty());
    }
}


Output

At 0:  80 
At 1:  36 
At 2:  47 
At 3:  23 
At 4:  99 

At 0:  80 
At 1:  36 
At 2:  92 47 
At 3:  23 
At 4:  49 99 

At 0:  80 
At 1:  36 
At 2:  92 47 
At 3:  23 
At 4:  49 

At 0:  
At 1:  
At 2:  
At 3:  
At 4:  
true

 



Similar Reads

Java Program to Implement Hash Table Chaining with List Heads
A hash table is a data structure that executes a connected array, it is a structure that maps keys to its values. It uses a hash function to calculate an index position for the keys, also called hash code. It will store key and value pair in an array of buckets, and from that bucket, the values can be easily found with the help of keys. To find the
4 min read
Java Program to Implement Hash Tables with Double Hashing
Double hashing is a technique in an open addressing scheme. and there is the ordinary hash function. In an open addressing scheme, the actual hash function is taking the ordinary hash function when its space is not empty then it will perform another hash function to get some space to insert. Double hashing is a collision resolving technique in an O
10 min read
Implementing our Own Hash Table with Separate Chaining in Java
All data structure has their own special characteristics, for example, a BST is used when quick searching of an element (in log(n)) is required. A heap or a priority queue is used when the minimum or maximum element needs to be fetched in constant time. Similarly, a hash table is used to fetch, add and remove an element in constant time. Anyone mus
10 min read
Java Program to Implement Hash Trie
A trie isn't something CS students might have spent that much time on in college but it's really very important for interviews. A trie is a data structure that is actually a type of tree, but it's often used to store an associative array or a dynamic set where the keys are usually characters or strings, and its position in the tree defines the key
7 min read
Java Program to Implement Direct Addressing Tables
Data structures are primarily used to store data and manage a large amount of data, and efficient data structures are helpful for developing better algorithms. The main operations performed on a data structure are Insert, Search, Update, and Delete. With increasing amounts of data, all these operations tend to take a large amount of time. There may
5 min read
How to Implement a Custom Hash function for Keys in a HashMap in Java?
In Java, HashMap is the data structure that implements the Map interface. This is used to save the data in the form of key-value pairs. In this article, we will learn how to implement a Custom Hash function for keys in a HashMap in Java. In Java, implementing the custom hash function for keys in a HashMap requires overriding the hashcode() method i
2 min read
Java Program to Rotate Doubly linked list by N nodes
Given a doubly linked list, rotate the linked list counter-clockwise by N nodes. Here N is a given positive integer and is smaller than the count of nodes in linked list. N = 2Rotated List: Examples: Input : a b c d e N = 2 Output : c d e a b Input : a b c d e f g h N = 4 Output : e f g h a b c d Asked in Amazon To rotate the Doubly linked list, we
4 min read
Java Program For Merge Sort For Doubly Linked List
Given a doubly linked list, write a function to sort the doubly linked list in increasing order using merge sort.For example, the following doubly linked list should be changed to 24810 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Merge sort for singly linked list is already discussed. The important change her
3 min read
Java Program For Deleting A Node In A Doubly Linked List
Pre-requisite: Doubly Link List Set 1| Introduction and Insertion Write a function to delete a given node in a doubly-linked list. Original Doubly Linked List  Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Approach: The deletion of a node in a doubly-linked list can be divided into three main categories:  After
4 min read
Java Program For Reversing A Doubly Linked List
Given a Doubly Linked List, the task is to reverse the given Doubly Linked List. See below diagrams for example. (a) Original Doubly Linked List (b) Reversed Doubly Linked List Here is a simple method for reversing a Doubly Linked List. All we need to do is swap prev and next pointers for all nodes, change prev of the head (or start) and change the
5 min read
three90RightbarBannerImg