Click here to Skip to main content
15,741,947 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to sort in alphabetical order a Linked List in java but my method only works with integers.

What I have tried:

public Node sort()
{

Node current;
Node sortedList = null;
int count;

if(first == null)
throw new IllegalArgumentException("List is empty");

// Creating a loop that will go through the whole list.
for (int index = 1; index < size(); index++)
{
// Redirects the unsorteNode variable to the second element in the list.
current = first.next;

// Redriects the scan variable to index.
count = index;

// Creating a loop that will go thorught the list and swap values.
while (count > 0 && current.value.compareTo(first.value) > 0)
{
sortedList = new Node(current.value, first);
first = first.next;
current = current.next;
count--;
}

// Switches the values in its correct position.
first.next = current;
}

// Returns the sorted list.
return sortedList;

}
Posted
Updated 26-Apr-18 0:06am
Comments
Richard MacCutchan 26-Apr-18 3:36am    
What is the definition of your node class, and how does the compareTo method operate?

1 solution

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900