java数据结构哈希表

增删查操作
Emp类

package com.m.demo9;

public class Emp {
	public int id;
	public String name;
	public Emp next;
	public Emp(int id, String name) {
		
		this.id = id;
		this.name = name;
	}
	@Override
	public String toString() {
		return "Emp [id=" + id + ", name=" + name + "]";
	}
	

}

链表类

package com.m.demo9;

public class EmpLinkedlist {
	Emp head=null;
	
	public void add(Emp emp) {
		
		if(head==null) {
			head=emp;
//			System.out.println(temp);
			return;
		}
		Emp temp=head;
		while(true) {
			if(temp.next==null) {
				break;//找到链表的最后一个
			}
			temp=temp.next;
		}
		temp.next=emp;
//		System.out.println(head);
		
	}
//	删除
	public void del(int id) {
		Emp temp=head;
		if(temp==null) {
			System.out.println("此条链表为空");
			return;
		}
//		是否需要删除头节点
		if(temp.id==id) {
			head=temp.next;
			return;
		}
		while(true) {
			
			if(temp.next!=null&&temp.next.id==id) {
				temp.next=temp.next.next;
				return;
			}
			
			if(temp.next==null) {
				break;
			}
			
			temp=temp.next;
			
			
		}
		System.out.printf("不存在id=%d的Emp\n",id);
//		if(temp.id==id) {//判断最后一个是不是需要删除的元素
//			temp=null;
//		}else {
//			System.out.printf("不存在id=%d的Emp\n",id);
//		}
	}
	public void show(int i) {
		Emp temp=head;
		if(temp==null) {
			System.out.printf("下标为%d的链表为空",i);
//			System.out.printf("链表为空");
			return;
		}
		System.out.printf("下标为%d的链表:",i);
//		System.out.printf("下标为%d的链表:");
		while(true) {
			System.out.print(temp+"=>");
			temp=temp.next;
			if(temp==null) {
				break;
			}
		}
	}

}


哈希表

package com.m.demo9;

public class Hashtable {
	private int size;
	private EmpLinkedlist[] emplist;
	public Hashtable(int size) {
		
		this.size = size;
		emplist=new EmpLinkedlist[size];
//		!!!!!初始化数组中的每一条链表!!!!!!!!!!!!
		for(int i=0;i<size;i++) {
			emplist[i]=new  EmpLinkedlist();
		}
	}
	
	//在哪一条链表添加->通过id计算
	public int index(int id) {
		return id%size;
	}
	
	public void add(Emp emp) {
		int i=index(emp.id);//在哪一条添加
		
		emplist[i].add(emp);
		
	}
	public void del(int id) {
		emplist[index(id)].del(id);
		
	}
	public void showlist() {
		for(int i=0;i<size;i++) {
			emplist[i].show(i);
			System.out.println();
		}
	}
}

测试类

package com.m.demo9;

public class Test {

	public static void main(String[] args) {
		Hashtable h=new Hashtable(3);
		h.add(new Emp(0,"小A"));
		h.add(new Emp(1,"小B"));
		h.add(new Emp(2,"小C"));
		h.add(new Emp(3,"小D"));
		h.add(new Emp(4,"小E"));
		h.showlist();
		h.del(5);
		h.del(0);
		System.out.println("======================");
		h.showlist();
//		EmpLinkedlist e=new EmpLinkedlist();
//		e.add(new Emp(1,"小A"));
//		e.show();
	}

}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值