浏览 206 次
|
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
|---|---|
| 作者 | 正文 |
|
最后更新时间:2008-03-30
哈希表分为两大类,一是开放地址法,二是链地址法。
1)、开放地址法中,通过在哈希表中再找一个空位解决冲突问题。 2)、链地址法中,某个数据项的关键字值还是像通常一样映射到哈希表的单元,而数据项本身插入到这个单元的链表中,其他同样映射到该位置的数据项只需要加入到链表中。 链地址法Java简缩代码: /** * 节点类 */ class Link{ private int data; public Link next; public Link(int data){ this.data = data; this.next = null; } public int getKey(){ return this.data; } public void display(){ System.out.println(this.data); } } /** * 优先级链表 */ class SortedList{ private Link first; public SortedList(){ this.first = null; } public void insert(Link theLink){ int key = theLink.getKey(); Link current = this.first; Link previous = null; while (current != null && key > current.getKey()){ previous = current; current = current.next; } if (previous != null){ previous.next = theLink; }else{ this.first = theLink; } theLink.next = current; } public Link find(int key){ Link current = this.first; while (current != null && key != current.getKey()){ current = current.next; } return current; } public void display(){ Link current = this.first; while (current != null){ current.display(); current = current.next; } } } /** * 链地址哈希表 */ class HashTableLink{ private SortedList[] hashArray; private int arraySize; public HashTableLink(int size){ this.arraySize = size; this.hashArray = new SortedList[this.arraySize]; for (int i = 0; i < this.arraySize; i++){ this.hashArray[i] = new SortedList(); } } public int keyFunc(int key){ return key % this.arraySize; } public void insert(Link theLink){ int key = keyFunc(theLink.getKey()); this.hashArray[key].insert(theLink); } public Link find(int key){ key = keyFunc(key); return this.hashArray[key].find(key); } public void display(){ for (int i = 0; i < this.arraySize; i++){ System.out.println("i: " + i); this.hashArray[i].display(); } } } public class HashTableTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub HashTableLink htl = new HashTableLink(3); for (int i = 1; i < 12; i ++){ Link link = new Link(i); htl.insert(link); } htl.display(); } } 声明:JavaEye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
|
|
| 返回顶楼 | |


