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


  • 我正在尝试以排序的方式将int元素添加到我的单链表中。但是输出是按随机顺序来的。有人能告诉我我的代码出了什么问题吗

这是我使用Generics 的Node.java类

/* 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)。我建议用一些测试数字在纸上运行算法,例如,在[2,5]中插入1,在[2.5]中插入3,在[2.5]中插入6。您可能还想测试重复的情况,例如在[1,2,2,3]中插入2。如果info小于current.getNext().getInfo(),则info.compareTo(current.getNext().getInfo())返回小于0的值,如果info大于current.getNext().getInfo(),则返回大于0的值。如果两个值相等,则返回0。

最新更新