增删查操作
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();
}
}