我有一个分配:
通过使用类节点来实现字符串对象的链接列表(请参阅Big> Java早期对象16.1.1(。编写方法,可以插入>和删除对象,并打印列表中的所有对象。>要求,列表中的所有元素始终按照字符串的自然顺序(可比(进行分类。
我似乎无法正确正确的方法是AddElement方法
整个班级都在这里:https://pastebin.com/swwn8ykz和主要应用:https://pastebin.com/a22mfdqk
我已经浏览了这本书(大爪哇早期对象(,并在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();
}
}
预期结果:列表中印刷的五个名称
实际结果:名字打印
给定此节点类:
private class Node {
public String data;
public Node next;
}
和private Node first;
的类级字段,最初是null
,以发出空白列表的信号加法可能是这样的:
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;
}
}
}
}
顺便说一句,还要尝试按顺序添加名称,以检查列表是否对其进行了分类(我在尝试使用时发现了一个错误(。