简体   繁体   English

用Java创建排序的链表

[英]Creating a sorted Linked List in Java

So I am supposed to sort a Linked List in Java by alphabetical order (The nodes are strings). 因此,我应该按字母顺序对Java中的链表进行排序(节点是字符串)。 I am not allowed to use Collections so I have to make up my own Linked List and sorting algorithm. 我不允许使用集合,因此我必须组成自己的“链表”和排序算法。 I have created a method that finds the largest (or furthest down the alphabet) word in the Linked List which work. 我创建了一种方法,该方法在可用的链接列表中找到最大(或在字母下方最远)的单词。 Now I am trying to sort by taking a linked List, finding the largest element and inserting it into a new linked list. 现在,我尝试通过获取链接列表,找到最大的元素并将其插入新的链接列表进行排序。 It then removes the largest and goes about doing the same until the Linked List is empty. 然后,它删除最大的并继续执行相同操作,直到“链表”为空。 I am ending up with a blank list when I run it, what is wrong with my code? 我运行它时最终得到一个空白列表,我的代码有什么问题?

Code that returns the largest element 返回最大元素的代码

public Link isLargest(){

    Link large = first;
    Link temp = null;
    Link current = first;
    Link after = current.next;

    while (after != null){

        if (large.lastName.compareTo(after.lastName) < 0){
            large = after;    
        }

        temp = current;
        current = temp.next;
        after = current.next;

    }
    return large;
}

To remove, I set the largest element to teh front then remove it. 要删除,我将最大的元素设置为front,然后将其删除。

 private static LinkedList linkSort(LinkedList unsorted){

    LinkedList sorted = new LinkedList();

    while (!(unsorted.isEmpty())){
        Link large = unsorted.isLargest();
        sorted.insert(large.name, large.lastName);
        first = large;
        unsorted.removeFront();
    }

    return sorted;
}

After you find the largest Link, you remove the Link at the head (removeFront) of the LinkedList. 找到最大的链接后,请删除LinkedList开头(removeFront)的链接。 This is incorrect, because the Link at the head is not necessarily the largest Link. 这是不正确的,因为最前面的链接不一定是最大的链接。 What you need to remove is the largest Link. 您需要删除的是最大的链接。

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

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