Advertisement
Guest User

Untitled

a guest
Nov 17th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.74 KB | None | 0 0
  1. class MyList {
  2.     protected int key;
  3.     protected int value;
  4.     protected MyList next;
  5.    
  6.     public MyList(int key, int value) {
  7.         this.key = key;
  8.         this.value = value;
  9.     }
  10. }
  11.  
  12. class MyHashMap {
  13.    
  14.     final int CAPACITY = 10000;
  15.    
  16.     protected MyList[] storage;
  17.  
  18.     public MyHashMap() {
  19.         this.storage = new MyList[CAPACITY];
  20.     }
  21.    
  22.     public void put(int key, int value) {
  23.         MyList node = this.storage[this.hash(key)];
  24.         if (node == null) {
  25.             this.storage[this.hash(key)] = new MyList(key, value);
  26.             return;
  27.         }
  28.         while (node != null) {
  29.             if (node.key == key) {
  30.                 node.value = value;
  31.                 return;
  32.             }
  33.             if (node.next == null) {
  34.                 node.next = new MyList(key, value);
  35.                 return;
  36.             }
  37.             node = node.next;
  38.         }
  39.     }
  40.    
  41.     protected int hash(int key) {
  42.         return key % CAPACITY;
  43.     }
  44.    
  45.     public int get(int key) {
  46.         MyList node = this.storage[this.hash(key)];
  47.         while (node != null) {
  48.             if (node.key == key) {
  49.                 return node.value;
  50.             }
  51.             node = node.next;
  52.         }
  53.         return -1;
  54.     }
  55.    
  56.     public void remove(int key) {
  57.         MyList node = this.storage[this.hash(key)];
  58.         if (node == null) {
  59.             return;
  60.         }
  61.         if (node.key == key) {
  62.             this.storage[this.hash(key)] = node.next;
  63.         }
  64.         while (node != null) {
  65.             if (node.next != null && node.next.key == key) {
  66.                 node.next = node.next.next;
  67.                 return;
  68.             }
  69.             node = node.next;
  70.         }
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement