gpt4 book ai didi

java - 如何将 addElement 方法写入已排序的 LinkedList?

转载 作者:行者123 更新时间:2023-12-02 02:17:47 25 4
gpt4 key购买 nike

我有一个作业:

implement a linked list of String objects by use of the class Node (see Big >Java Early Objects 16.1.1). Write methods, that make it possible to insert >and delete objects, as well as print all objects in the list. It is a >requirement that all elements in the list are sorted, at all times, according >to the natural ordering of Strings(Comparable).

我似乎无法正确使用的方法是 addElement 方法

全类同学都在这里:https://pastebin.com/Swwn8ykZ主应用程序:https://pastebin.com/A22MFDQk

我读过这本书(Big Java Early Objects),也看过 geeksforgeeks

public void addElement(String e) {
Node newNode = new Node();
if (first.data == null) {
first.data = e;
System.out.println("Success! " + e + " has been
added!");
} else if (first.data.compareTo(e) == 0) {
System.out.println("The element already exists in the
list");
} else {
while (first.next != null) {
if (first.next.data.compareTo(e) != 0) {
first.next.data = e;
} else {
first.next = first.next.next;
}
}
}
}

public static void main(String[] args) {
SortedLinkedList list = new SortedLinkedList();

String e1 = new String("albert");
String e2 = new String("david");
String e3 = new String("george");
String e4 = new String("jannick");
String e5 = new String("michael");

// ----------------SINGLE LIST--------------------------
list.addElement(e1);
list.addElement(e2);
list.addElement(e3);
list.addElement(e4);
list.addElement(e5);

System.out.println("Should print elements after this:");
list.udskrivElements();
}
}

预期结果:五个名字打印在列表中

实际结果:打印的名字

最佳答案

给定这个 Node 类:

private class Node {
public String data;
public Node next;
}

和一个 private Node first; 的类级字段,最初为 null 表示一个空列表,addElement 可能是这样的:

public void addElement(String text) {
if (text == null) return; // don't store null values

Node extra = new Node();
extra.data = text;

if (first == null) {
// no list yet, so create first element
first = extra;
} else {
Node prev = null; // the "previous" node
Node curr = first; // the "current" node

while (curr != null && curr.data.compareTo(text) < 0) {
prev = curr;
curr = curr.next;
}

if (curr == null) {
// went past end of list, so append
prev.next = extra;
} else if (curr.data.compareTo(text) == 0) {
System.out.println("Already have a " + text);
} else {
// between prev and curr, or before the start
extra.next = curr;
if (prev != null) {
prev.next = extra;
} else {
// append before start, so 'first' changes
first = extra;
}
}
}
}

顺便说一下,还可以尝试以未排序的顺序添加名称,以检查列表是否对它们进行排序(当我尝试这样做时,我在代码中发现了一个错误)。

关于java - 如何将 addElement 方法写入已排序的 LinkedList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57291231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com