繁体   English   中英

以排序方式在链表中插入元素

[英]Inserting elements in a linked list in a sorted way

我正在尝试以排序方式将 int 元素添加到我的单链表中。 但 output 的顺序是随机的。 我的代码有什么问题?

这是我的 Node.java class 我正在使用 Generics

/* Node.java */
public class Node<E>{
    private E info;
    private Node<E> next;

    public Node(){
        this.next = null;
    }

    public Node(E info){
        this.info = info;
        this.next = null;
    }
    public Node(E info, Node<E> next){
        this.info = info;
        this.next = next;
    }

    public E getInfo(){
        return this.info;
    }
    public void setInfo(E info){
        this.info = info;
    }
    public Node<E> getNext(){
        return this.next;
    }

    public void setNext(Node<E> next){
        this.next = next;
    }

}

在 main 方法中,我创建了一个链表并使用 Math.random() 方法 - 我试图将 int 元素插入到我的链表中

/* Main Method */

public class SortedInsertionLinkedList{

    public static void main(String args[]){
        // Create a linked list using MyLinkedList<Integer>
        MyLinkedList<Integer> mine = new MyLinkedList<Integer>();
       // Insert 10 ints 
        for (int i=0; i< 10; i++){
            mine.insert((int)(100*Math.random()));
        }
        
        //Print the whole list
        mine.print();
    }
}

在链表的实现中,我使用的是 compareTo() 方法

/* Linked list implementation */

public class MyLinkedList<E extends Comparable<E>>{
   
    private Node<E> first;
    
    public MyLinkedList(){
        this.first = null;
    }
    
       public void insert(E info){
        Node<E> newNode = new Node<E>(info);
        
        if(first == null || info.compareTo(first.getInfo()) < 0 ) {
            newNode.setNext(first);
            first = newNode;
        } else {
            Node<E> current = first;
            while(current.getNext() != null && info.compareTo(current.getNext().getInfo()) < 0)
            {
                current = current.getNext();
                
            }
            newNode.setNext(current.getNext());
            current.setNext(newNode); 
        }
        }
        
    
    public void print(){
        Node<E> current = first;
        
        while (current != null){
            System.out.print(current.getInfo() + " ");
            current = current.getNext();
        }
        System.out.println();
    }
}

您的 while 语句需要是while(current.getNext().= null && info.compareTo(current.getNext().getInfo()) > 0) 我建议使用一些测试数字在纸上运行算法 - 例如,将 1 插入 [2,5],将 3 插入 [2,5],将 6 插入 [2,5]。 您可能还想测试重复的情况,例如将 2 插入 [1,2,2,3]。 如果info小于current.getNext().getInfo()info.compareTo(current.getNext().getInfo())返回小于 0 的值,如果info大于 current.getNext().getInfo,则返回大于 0 的current.getNext().getInfo() 如果两个值相等,则返回 0。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM