package com.guge.test; import java.util.Random; /** * Created by guugangzhu on 2017/6/1. */ public class HashLink { public static void main(String[] args) { HashLink hashLink=new HashLink(59); Random random=new Random(); for (int i = 0; i <100 ; i++) { Link link=new Link(random.nextInt(500)); hashLink.insert(link); } hashLink.displayTable(); } private SortedList[] hashArray; private int arraySize; public HashLink(int size){ arraySize=size; hashArray=new SortedList[arraySize]; for (int i = 0; i < arraySize; i++) { hashArray[i]=new SortedList(); } } public void displayTable(){ for (int i = 0; i < arraySize; i++) { System.out.print(i+" "); hashArray[i].displayList();; } } public int hashFunc(int key){ return key%arraySize; } public void insert(Link theLink){ int hashVal=hashFunc(theLink.getKey()); hashArray[hashVal].insert(theLink); } public void delete(int key){ int hashVal=hashFunc(key); hashArray[hashVal].delete(key); } public Link find(int key){ int hashVal=hashFunc(key); return hashArray[hashVal].find(key); } } class Link{ private int iData; public Link next; public Link(int it){ iData=it; } public int getKey(){ return iData; } public void displayLink(){ System.out.print(iData+" "); } } class SortedList{ private Link first; public SortedList(){ first=null; } public void insert(Link theLink){ int key=theLink.getKey(); Link previous=null; Link current=first; while (current!=null&&key<current.getKey()){ previous=current; current=current.next; } if(previous==null) first=theLink; else previous.next=theLink; theLink.next=current; } public void delete(int key){ Link previous=null; Link current=first; while (current!=null&&key!=current.getKey()){ previous=current; current=current.next; } if(previous==null&&first!=null) first=first.next; if(previous!=null&¤t!=null){ previous.next=current.next; } } public Link find(int key){ Link current=first; while (current!=null&&key<current.getKey()){ if(key==current.getKey()){ return current; } current=current.next; } return null; } public void displayList(){ System.out.println("List(first-->last)"); Link current=first; while (current!=null){ current.displayLink(); current=current.next; } System.out.println(""); } }
java 链表哈希表
最新推荐文章于 2023-10-09 19:37:45 发布