[英]Trouble sorting linked list
output我正在為 class 做一個項目,我必須使用插入排序對鏈表進行排序。 我應該接受用戶輸入,將其轉換為 int 數組並將其插入到鏈表中。 我的問題是由於某種原因,當我 go 打印鏈表后排序時,它只打印第一個節點。 當我最初測試它時,代碼運行良好(我手動輸入要插入的整數),但現在我使用的是 arrays 它似乎不起作用。 任何人都可以幫忙嗎?
(這只是我項目中的一個 class,但如果需要更多信息,請告訴我)。 編輯:我添加了一張我的 output lokos 喜歡的圖片
import java.util.Arrays;
public class SortLL {
static LL top;
static Node head;
static Node sorted;
//function to insert node at head
public void toHead(int newData){
Node newNode = new Node(newData);
newNode.link = head;
head = newNode;
}
public static void insertion(Node ref){ //problem right now is that i'm only passing in one node
sorted = null;
Node current = ref;
while(current != null){
Node next = current.link;
sortInsert(current);
current = next;
}
head = sorted;
}
static void sortInsert(Node newNode){ //item in this case is val
if(sorted == null || sorted.item >= newNode.item){
newNode.link = sorted;
sorted = newNode;
} else {
Node current = sorted;
while(current.link != null && current.link.item < current.item){
current = current.link;
}
newNode.link = current.link;
current.link = newNode;
}
}
void printList(Node head)
{
while (head != null)
{
System.out.print(head.item + " ");
head = head.link;
}
}
public static void sortList(int[] arrA, int[] arrB){
int[] arr = new int[arrA.length + arrB.length];
System.arraycopy(arrA, 0, arr, 0, arrA.length);
System.arraycopy(arrB, 0, arr, arrA.length, arrB.length);
System.out.println("checking array " + Arrays.toString(arr));
SortLL sort = new SortLL();
for(int i=0;i<arr.length;i++){
sort.toHead(arr[i]);
}
System.out.println("sortLL.java\n\n");
sort.printList(sort.head);
sort.sortInsert(sort.head);
System.out.println("\nLinkedList After sorting");
sort.printList(sort.head);
}
}
在您的printList()
方法中,您在遍歷列表時移動 head 變量。 當您將 head 變量移動到末尾時,您實際上破壞了鏈表,因為您失去了對它開頭的引用。 Java 將自動將未引用的節點視為垃圾。
據我所知,在您第一次調用sort.printList(sort.head)
之后,您破壞了原始鏈表,因此在排序時它不起作用。
調用printList()
時,使用臨時節點( Node temp = head
)可能會有所幫助,這樣您就不會丟失原始的 head 變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.