[英]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.