Каждый раз, когда я хочу вставить новый узел в список, он создаст новую голову, которую он должен сделать в первый раз, но во второй раз он должен привязать новый узел к предыдущему. Всякий раз, когда я вставляю этот код, он продолжает создавать новую голову. Почему предыдущая голова, которая была впервые вставлена, не сохраняется?Сортировка списка вставки продолжает создавать новую голову?
static class TreeNode{
int frequency;
boolean isLeftChild;
TreeNode parent;
TreeNode next;
/**
* TreeNode class constructor to initialize the variables and also
* takes a frequency as the parameter.
* @param f Frequency of a certain character.
*/
TreeNode(int f){
frequency = f;
isLeftChild = true;
parent = null;
next = null;
}
}
// Class used to store information for the linked list.
static class List{
TreeNode head;
int numItems; // number of nodes in the list
List(){
head = null;
numItems = 0;
// initialize head and numItems
}
/**
* Inserts a node into the TreeNode linked list according to its frequencies
* position as it will be in a SORTED list.
* @param freq Frequency of a specific character.
* @return Returns the new TreeNode object that has been inserted.
*/
TreeNode insert(int freq){
TreeNode previous, current, newNode;
int newFreq = freq;
numItems++;
previous = null;
current = head;
while((current != null) && (Integer.valueOf(newFreq).compareTo(Integer.valueOf(current.frequency)) > 0)){
previous = current;
current = current.next;
}
if(previous == null){
head = new TreeNode(newFreq);
return head;
}
else{
newNode = new TreeNode(newFreq);
previous.next = newNode;
return newNode;
}
}
Почему вы никогда не установить следующий указатель нового узла? –
Что произойдет, если вы попытаетесь вставить что-то меньшее, чем текущая частота головы? –
Я думаю, что у меня есть хорошее предположение о том, что здесь не так. Можете ли вы сказать мне, какие значения вы вставляете? –