无法对链表进行排序

托尼·特兰

输出我正在为类做一个项目,我必须使用插入排序对链接列表进行排序。我应该接受用户输入,将其转换为 int 数组并将其插入到链表中。我的问题是出于某种原因,当我去打印链表后排序时,它只打印第一个节点。当我最初测试它时,代码工作得很好(我手动输入要插入的整数),但现在我使用的是数组,它似乎不起作用。任何人都可以帮忙吗?

(这只是我项目中的一门课,但如果需要更多信息,请告诉我)。编辑:我添加了我的输出 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 变量。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章