如何用JAVA做链接,如何在Java中实现链接列表?

I am trying to implement a simple HashTable in Java that uses a Linked List for collision resolution, which is pretty easy to do in C, but I don't know how to do it in Java, as you can't use pointers...

First, I know that those structures are already implemented in Java, I'm not planning on using it, just training here...

So I created an element, which is a string and a pointer to the next Element:

public class Element{

private String s;

private Element next;

public Element(String s){

this.s = s;

this.next = null;

}

public void setNext(Element e){

this.next = e;

}

public String getString(){

return this.s;

}

public Element getNext(){

return this.next;

}

@Override

public String toString() {

return "[" + s + "] => ";

}

}

Of course, my HashTable has an array of Element to stock the data:

public class CustomHashTable {

private Element[] data;

Here is my problem:

For example I want to implement a method that adds an element AT THE END of the linked List (I know it would have been simpler and more efficient to insert the element at the beginning of the list, but again, this is only for training purposes). How do I do that without pointer?

Here is my code (which could work if e was a pointer...):

public void add(String s){

int index = hash(s) % data.length;

System.out.println("Adding at index: " + index);

Element e = this.data[index];

while(e != null){

e = e.getNext();

}

e = new Element(s);

}

Thanks!

解决方案

public void add(String s){

int index = hash(s) % data.length;

System.out.println("Adding at index: " + index);

Element curr = new Element(s);

Element e = this.data[index];

if (e == null) {

this.data[index] = curr;

return;

}

while(e.getNext() != null){

e = e.getNext();

}

e.setNext(curr);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值