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

查看:30
本文介绍了如何在 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...

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

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 数组来存储数据:

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

public class CustomHashTable {
    private Element[] data;

这是我的问题:

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

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天全站免登陆