如何在Java中实现链接列表? [英] How to implement a Linked List in Java?

查看:518
本文介绍了如何在Java中实现链接列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Java中实现一个简单的HashTable,它使用链接列表进行冲突解决,这在C中很容易做到,但我不知道如何用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...

首先,我知道这些结构已经用Java实现了,我不打算使用它,只是在这里训练......

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 + "] => ";
        }
    }

当然,我的HashTable有一个Element to数组库存数据:

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

public class CustomHashTable {
    private Element[] data;

这是我的问题:

For示例我想实现一个方法,在链接列表的末尾添加一个元素(我知道在列表的开头插入元素会更简单,更有效,但同样,这仅用于培训目的) 。如果没有指针我该怎么做?

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?

这是我的代码(如果e是一个指针,它可以工作......):

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

谢谢!

推荐答案

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

这篇关于如何在Java中实现链接列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆