【发布时间】:2014-04-18 18:00:21
【问题描述】:
每次我想在列表中插入一个新节点时,它都会创建一个新的头,第一次它应该这样做,但第二次它应该将新节点附加到前一个节点。每当我插入此代码时,它都会不断创建一个新的头部。为什么之前插入的head没有保存?
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;
}
}
【问题讨论】:
-
为什么从不设置新节点的next指针?
-
如果您尝试插入低于当前头部频率的内容会怎样?
-
我想我可以很好地猜到这里出了什么问题。您能告诉我您要插入哪些值吗?
-
@liangricha 我正在为每个 TreeNode 对象插入不同的频率。只要频率大于 0,它就会被插入到列表中。它也是使用排序列表插入方法,使得链表上的头部成为最小值。
-
您插入了哪些频率导致了错误?
标签: java tree linked-list sortedlist