public class Linkedlist {
public class Node{
private Person p;
private Node next;
public Node(Person p){
this.p=p;
}
/**
* @return the p
*/
public Person getP() {
return p;
}
/**
* @param p the p to set
*/
public void setP(Person p) {
this.p = p;
}
}
private Node head;
private String key;
public Linkedlist(){
head=new Node(null);
head.next=head;
}
public void insertNode(Person p){
Node node=new Node(p);
Node temp=head;
if(head.next!=head){
while(temp.next!=head){
temp=temp.next;
}
temp.next=node;
node.next=head;
}else{
head.next=node;
node.next=head;
}
}
public Node find(String key){
Node temp=head;
if(temp.next!=head){
while(!key.equals(temp.next.p.getAge())){
temp=temp.next;
}
return temp.next;
}else{
return null;
}
}
public int delete(String key){
Node temp=head;
if(temp.next!=head){
while(!key.equals(temp.next.p.getAge())){
temp=temp.next;
}
temp.next=temp.next.next;
return 1;
}else{
return -1;
}
}
public void deleteNode(){ //從頭結(jié)點開始刪除
if(head.next!=head){
head.next=head.next.next;
}else{
System.out.println("沒有可刪除的節(jié)點");
}
}
public void display(){
Node temp=head;
while(temp.next!=head){
temp=temp.next;
System.out.println(temp.p);
}
}
}
import java.math.BigInteger;
public class Hashmap {
private Linkedlist[] arr;
public Hashmap(int maxnum){
arr=new Linkedlist[maxnum];
}
public void insert(Person p){
int key=hashCode(p.getAge());
if(arr[key]==null){
arr[key]=new Linkedlist();
}
arr[key].insertNode(p);
}
/*查找數(shù)據(jù)
*
* */
public Person find(String age) {
return arr[hashCode(age)].find(age).getP();
}
public void delete(String age){
int key=hashCode(age);
System.out.println(arr[key].delete(age));
}
public int hashCode(String age){
BigInteger hashVal=new BigInteger("0");
BigInteger pow27=new BigInteger("1");
for(int i=age.length()-1;i>=0;i--){
int letter=age.charAt(i)-96;
BigInteger letterB=new BigInteger(String.valueOf(letter));
hashVal=hashVal.add(letterB.multiply(pow27));
pow27=pow27.multiply(new BigInteger(String.valueOf(27)));
}
return hashVal.mod(new BigInteger(String.valueOf(arr.length))).intValue();
}
}
public class TestHash {
public static void main(String[] args) {
Hashmap h=new Hashmap(4);
Person p1=new Person("a","李四");
Person p2=new Person("ct","王五");
Person p3=new Person("b","張三");
h.insert(p1);
h.insert(p2);
h.insert(p3);
//h.delete("b");
System.out.println(h.find("b"));
System.out.println(h.find("a"));
System.out.println(h.find("ct"));
}
}
最后編輯于 :
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者