public class HashTable { public static final int CAPACITY = 10; private Node[] value = null; public static void main(String[] args) { HashTable hashtable = new HashTable(); hashtable.insertData(22); hashtable.insertData(22); hashtable.insertData(123); hashtable.insertData(436); hashtable.insertData(55); hashtable.insertData(157); hashtable.insertData(235); hashtable.insertData(256); hashtable.insertData(525); hashtable.insertData(724); hashtable.insertData(278); hashtable.insertData(209); hashtable.insertData(67); hashtable.insertData(54); hashtable.insertData(546); hashtable.insertData(350); hashtable.insertData(101); hashtable.insertData(23); hashtable.printHashTable(); hashtable.deleteData(55); hashtable.deleteData(350); hashtable.printHashTable(); } public HashTable() { value = new Node[CAPACITY]; } //在哈希表中查找数据 private Node searchData(int data) { Node node = value[data % CAPACITY]; if(null == node) { return null; } while(node != null) { if(data == node.key) { return node; } node = node.next; } return null; } //插入数据 private boolean insertData(int data) { Node nd = value[data % CAPACITY]; if(null == nd) { Node node = new Node(data); value[data % CAPACITY] = node; return true; } //如果已经有这个值了,插入无效 if(null != searchData(data)) { return false; } while(nd.next != null) { nd = nd.next; } nd.next = new Node(data); return true; } private boolean deleteData(int data) { Node head = value[data % CAPACITY]; Node node = searchData(data); if(null == head || null == node) { return false; } if(node == head) { //删除时要注意,head只是栈内存中的引用 value[data % CAPACITY] = head.next; return false; } while(node != head.next) { head = head.next; } head.next = node.next; return true; } void printHashTable() { int i=0; System.out.println("[Hash idx] [value]"); do { System.out.print(" "+i+"-------------"); if(null == value[i]) { i++; System.out.println("NULL"); continue; } Node node = value[i]; while(node != null) { System.out.print(node.key+" "); node = node.next; } System.out.println(); i++; } while (i<10); System.out.println(); } private static class Node { int key = 0; Node next = null; public Node(int key) { this.key = key; } } }
时间: 2024-10-12 22:09:41