简体   繁体   中英

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). 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.

 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. This is incorrect, because the Link at the head is not necessarily the largest Link. What you need to remove is the largest Link.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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