在一个类中将对象添加到链接列表的末尾

hac*_*boy 5 java methods class linked-list

我对LinkedList有点新,我想通过在ExampleLinkedList类中创建方法来练习.test3中有一个列表.当我打电话给test3时,我得到了再见谢谢你好.我想要的是在列表的末尾添加"AddedItem"以获得AddedItem再见谢谢你好,但我只得到AddedItem.如何在不编写新类的情况下修复addToEnd方法.

public class ExampleLinkedList 
{
    private String data;
    private ExampleLinkedList next;

    public ExampleLinkedList(String data,ExampleLinkedList next)
    {
        this.data = data;
        this.next = next;
    }

    public void addToEnd(String item)
    {
        while(next != null)
        {
            data = item;
            next.data = data;
            next = next.next;   
        }
    }

    public boolean isEmpty()
    {
        if(next == null)
        {
            return true;
        }
        return false;
    }

    public String toString()
    {
        String result = data;
        while(next != null)
        {
            result = result + " " + next.data;
            next = next.next;
        }
        return result;
    }

}

public class Test 
{     

    public static void main(String[] args) 
    {
        ExampleLinkedList test1 = new ExampleLinkedList("Hello", null);
        ExampleLinkedList test2 = new ExampleLinkedList("Thanks", test1);
        ExampleLinkedList test3 = new ExampleLinkedList("Goodbye", test2);

        test3.addToEnd("AddedItem");
        System.out.println(test3);
    }
}
Run Code Online (Sandbox Code Playgroud)

pat*_*ite 3

这应该有效。它将设置item为链表的头

public void addToEnd(String item)
{
    ExampleLinkedList newNode = new ExampleLinkedList(data, next);
    data = item;
    next = newNode;
}
Run Code Online (Sandbox Code Playgroud)