[英]How do I write an addElement method to a sorted LinkedList?
我有一個任務:
使用類 Node 實現 String 對象的鏈接列表(請參閱 Big > Java Early Objects 16.1.1)。 編寫方法,可以插入 > 和刪除對象,以及打印列表中的所有對象。 >要求列表中的所有元素始終根據字符串(Comparable)的自然順序進行排序。
我似乎無法理解的方法是 addElement 方法
整個班級在這里: https ://pastebin.com/Swwn8ykZ 和 mainApp: 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;
是private Node first;
的類級別字段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;
}
}
}
}
順便說一句,還要嘗試按未排序的順序添加名稱,以檢查列表是否對它們進行了排序(嘗試時在代碼中發現了一個錯誤)。
像這樣定義一個Node
:
class Node
{
int data;
Node next;
}
下面的方法將元素插入到排序順序:
void sortInsert(Node new_node){
Node current;
if (head == null || head.data >= new_node.data)
{
new_node.next = head;
head = new_node;
}
else {
current = head;
while ( current.next.data < new_node.data && current.next != null)
current = current.next;
new_node.next=current.next;
current.next=new_node;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.