简体   繁体   中英

Alphabetically sort a linked list in Java

I've spend 3 hours searching and attempting to make algorithms myself. I can't figure it out, can someone give me an algorithm to Sort a Linked List Alphabetically?

Here is the last thing I attempted before I gave up the search and decided to ask here

class link
{
public void insertNewFirstNode(String value)
{
    StringNode newNode = new StringNode(value, head);
    head = newNode;
    if(tail==null)
    {
        tail=head;
    }
}

public link sort(link L)
{
   link sorted = new link(); 
   StringNode currentNode = head; 
   while (currentNode != null) 
   {
       int data=0;

       if((currentNode.getLink() != null))
       {
       data=currentNode.getData().compareTo(currentNode.getLink().getData());
                if(data==1)
                {
                    sorted.insertNewFirstNode(currentNode.getData());
                }            
                currentNode = currentNode.getLink();  

       }
       else if((currentNode != null))
       {                      

           currentNode = currentNode.getLink();  
       }
    }
   sorted.reverse();
   return sorted;
 }
//Other functions
}

Sorting a LinkedList is O(n 2 *log(n)), since it takes O(n) time to iterate through the list to find a position and O(n*log(n)) to sort it. So, the best thing to do would be to turn the list into an array, sort the array, and then iterate through the array and set the nodes in the list to their proper order, which is O(n+n*log(n)).

This is exactly what Collections.sort() does (uses merge sort). All you need to do is override your .compareTo() such that you sort based on alphabetical ordering and have StringNode implement Comparable<StringNode> .

Alternatively, you can do something like:

Collections.sort(myList, new Comparator<StringNode>() {
    public int compare(StringNode node1, StringNode node2) {
          return node1.getData().compareTo(node2.getData());
    }
});

NB:
Your myList class must implement List , or extend something that does.

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