为什么我不能用这个java代码对用户定义的LinkedList进行排序?

时间:2016-07-19 14:13:06

标签: java sorting linked-list singly-linked-list

我在 JAVA 中创建了一个程序,用于向LinkedList添加元素,并在添加元素时对其进行排序。我在排序时使用的交换技术类似于将节点添加到LinkedList的开头时使用的技术。该技术适用于后一种情况,但未能在前者中运行。我不明白为什么这不起作用。以下是我的代码供您参考。

//Node class
class Node{
    int d; Node link;
    Node(int d){
        this.d = d;
        link = null;
    }
}//Node

//LinkedList class
class LL{
    Node start;
    LL(){
        start = null; 
    }

    //method to add and sort the nodes 
    //in ascending order of the values of 'd' of the nodes
    void insert(Node nd){
        if(start==null){
            start = nd;
        }
        else{
            Node temp = start;
            while(temp!=null){
                if(nd.d<=temp.d){
                    Node t2 = temp;
                    temp = nd;
                    nd.link = t2;
                    break;
                }
                temp = temp.link;
            }
        }
    }//insert

    //method to display nodes of the LinkedList
    void display(){
        Node temp = start;
        do{
            System.out.print(temp.d + " ");
            temp = temp.link;
        }while(temp!=null);
    }//display
}//LL

//Main class
class LL_Test{
    public static void main(String[] args){
        LL myLL = new LL();
        myLL.insert(new Node(5));
        myLL.insert(new Node(2));
        myLL.insert(new Node(7));
        myLL.insert(new Node(6));
        myLL.insert(new Node(1));
        myLL.display();
    }//main
}//LL_Test

预期输出1 2 5 6 7
获得的输出5

3 个答案:

答案 0 :(得分:2)

除了第一个元素之外,你永远不会在列表中添加元素。 (temp = nd;未将上一个节点的链接设置为nd)。您需要跟踪上一个节点并在元素之前添加新节点,然后在第一个节点大于您想要的节点之前

void insert(Node nd) {
    Node temp = start;
    Node previous = null;

    while (temp != null && temp.d < nd.d) {
        previous = temp;
        temp = temp.link;
    }

    // insert node
    if (previous == null) {
        // insert at start
        nd.link = start;
        start = nd;
    } else {
        // insert somewhere in the middle
        nd.link = temp;
        previous.link = nd;
    }
}//insert

答案 1 :(得分:1)

两条评论,均适用于insert()循环内的start != nullwhile(temp!=null)

  1. 条件不太正确(我认为) - 对于升序,您希望向前跳过,直到找到temp.d <= nd.d temp.link==null或{的节点为止{1}}。
  2. temp.link.d >= nd.dwhile循环的正文中,设置insert,以便新节点指向另一个节点。但是,您没有设置nd.link或类似的东西来将新节点挂钩到从temp.link=nd开始的链中。

答案 2 :(得分:1)

我对此的看法:

void insert ( Node nd )
{
    Node temp = start;
    Node previous = null;
    while ( temp != null )
    {
        if ( nd.d <= temp.d )
        {
            nd.link = temp;
            if ( nd.d < start.d )
            {
                start = nd;
            }
            break;

        }
        previous = temp;
        temp = temp.link;
    }
    if( previous != null )
    {
        previous.link = nd;
    }
    if( start == null )
    {
        start = nd;
    }


}
相关问题