哈希表链地址法c语言程序,哈希表 链地址法

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(){ //从头结点开始删除

if(head.next!=head){

head.next=head.next.next;

}else{

System.out.println("没有可删除的节点");

}

}

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);

}

/*查找数据

*

* */

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"));

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值