Я создал Связанный список с нуля и добавил методы, такие как add , remove , set , size и т. Д. I Также добавлен простой статический и рекурсивный sort метод, который принимает ссылку на связанный список в качестве параметра, чтобы его можно было использовать в классе Main. Вызывается как sort(linkedList);
и возвращает отсортированный связанный список.
Программа выдает Exception in thread "main" java.lang.StackOverflowError
, в строках if (biggest.compareTo(nextNode.value) < 0) biggest = nextNode.value;
и return sort(list);
. Я хочу, чтобы метод сортировки сортировал список в алфавитном порядке (мой связанный список состоит из элементов String).
Это метод в коде:
/**
* The sort method sorts the list in alphabetical order
* @param list list to be sorted
* @return sorted linked list
*/
static DD_RecursiveLinkedList sort(DD_RecursiveLinkedList list) {
DD_Node nextNode = head.next;
String biggest = head.value, smallest = tail.value; //by default biggest is the head, and smallest is the tail
if (isEmpty()) return null; //if list is empty, return null
do { //find the biggest and smallest value in the list
if (biggest.compareTo(nextNode.value) < 0) biggest = nextNode.value; //if nextNode is bigger than the biggest, biggest is nextNode
if (smallest.compareTo(nextNode.value) > 0) smallest = nextNode.value; //if nextNode is smaller than the smallest, smallest is nextNode
nextNode = nextNode.next; //update nextNode
} while (nextNode!=null); //loop until nextNode is null
set(0, biggest); set(size()-1, smallest); //set biggest as the head of the list, and smallest as the tail
// remove(biggest);//remove the biggest (head) from the list
// remove(smallest); //remove the smallest (tail) from the list
// list.add(0, biggest); //add the biggest to the sorted list as head element
// list.add(size()-1, smallest); //add the smallest to the sorted list as tail element
return sort(list); //sort the order of sorted list recursively
}
Я закомментировал строки add
и remove
, потому что они были включены в ошибку, поэтому вместо методов add
и remove
я использовал метод set
, чтобы заменить элемент по указанному индексу с указанным элементом.