为什么我不能用此Java代码对用户定义的LinkedList进行排序? [英] Why can't I sort a user defined LinkedList with this java code?

查看:115
本文介绍了为什么我不能用此Java代码对用户定义的LinkedList进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 JAVA 中创建了一个程序,用于将元素添加到LinkedList并在添加元素时对其进行排序.我在排序时使用的 swap 技术类似于在LinkedList的开始中添加节点时使用的技术.该技术在后一种情况下有效,但在前一种情况下无法运行.我不明白为什么这行不通.以下是我的代码供您参考.

I created a program in JAVA to add elements to a LinkedList and sort the elements while adding them. The swap technique I'm using in case of sorting is similar to that used while adding a node to the beginning of the LinkedList. The technique works in the latter case but fails to run in the former. I don't understand why this is not working. Below is my code for your reference.

//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

推荐答案

您实际上从未将除第一个元素外的任何元素添加到列表中. (temp = nd;不会将前一个节点的链接设置为nd).您需要跟踪上一个节点,并在第一个大于您想要的节点的第一个之前的元素之后添加新的节点

You never actually add a element except the first to the list. (temp = nd; does not set the link of the previous node to nd). You need to keep track of the previous node and add the new one after the element before the first one larger than the one you want to

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

这篇关于为什么我不能用此Java代码对用户定义的LinkedList进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆