【问题标题】:Java Self-Programmed Singly-Linked-List in Linked-List链表中的Java自编程单链表
【发布时间】:2023-03-15 01:46:01
【问题描述】:

至少对我来说,我在大学里有一个棘手的练习要做。任务是用各种方法编写一个单链表。到目前为止很容易,但挑战是之后将这些单链表存储在链表中。在下面,您会看到我的单链表实现,它实际上运行顺利:

public class Liste {

ListenElement first;
ListenElement last;
ListenElement current;
int count;

public Liste() {
    first = null;
    last = null;
    current = null;
    count = 0;
}

// Methods...

单链表由以下实现的列表元素组成:

public class ListenElement {

String content;
ListenElement next;

public ListenElement(String content, ListenElement next)
{
    this.content = content;
    this.next = next;
}

//Methods...

这是我的问题:

LinkedList<Liste> zeilen = new LinkedList<>();
Liste zeile1 = new Liste();
Liste zeile2 = new Liste();

zeile1.addBehind("Hello");
zeile1.addBehind("World");
zeile2.addBehind("Hello");
zeile2.addBehind("World");

zeilen.add(zeile1);
zeilen.add(zeile2);

System.out.print(zeilen.get(1));
//Printed: Listen.Liste@4aa298b73 instead of Hello World.

提前感谢您的帮助!

【问题讨论】:

  • 您的代码甚至从未调用过zeilen.add()。我们如何为您调试?
  • 感谢蒂姆的评论!出于什么原因,我通过创建问题而失去了这一部分。我已经更新了问题。

标签: java linked-list singly-linked-list


【解决方案1】:
System.out.print(zeilen.get(1));

//打印:Listen.Liste@4aa298b73 而不是 Hello World。

这是默认Object#toString 的输出。如果您想要 Liste 类的不同输出,则需要覆盖 toString 以提供不同的输出。

例如:如果您希望Liste#toString 返回其内容的toStrings 的逗号分隔列表:

@Override
public String toString() {
    StringBuffer sb = new StringBuffer(10 * this.count); // Complete guess
    ListenElement el = this.first;
    while (el != null) {
        sb.append(el.content.toString());
        el = el.next;
        if (el != null) {
            sb.append(", ");
        }
    }
    return sb.toString();
}

(根据您显示的代码,我正在假设您的列表类的工作方式......)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多