每次我想在列表中插入一个新节点时,它会创建一个新头,它应该第一次执行,但第二次应该将新节点附加到前一个节点。每当我使用此代码插入时,它都会不断创建新头。为什么先插入的头部没有被保存?
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;
}
}
答案 0 :(得分:0)
如果头只应该创建一次,那么构造函数的用途是什么!
List() {
// initialize head here
head = new Node();
head.next = head;
head.previous = head;
}
另外,我认为您需要更长时间地考虑一下您希望列表的节点看起来像什么。我是否正确理解您是否正在尝试创建双向链接排序列表?如果是这样,如果其节点包含Comparabe
类型的数据对象,则它可能最常用,因此您可以将该列表重用于其他目的。 (甚至更高兴的是将其数据类型设为通用Comparable<T>
。)
最后,如果您尝试在列表中存储字母频率,那么数据类型将需要有两个字段,一个用于字母的频率,另一个用于字母&#39;计数。而且你必须决定你想要用于排序的两个中的哪一个:角色或频率。我期待这个角色。
无论如何,在开始编码之前,先尝试先绘制一张你想做的小图片。
答案 1 :(得分:0)
让我来点一下:
假设您首先按顺序插入频率为5和4的TreeNode
。如您所说,第一次插入将按预期进行。当您尝试插入频率为4的TreeNode
时,会立即绕过while(...)
,这意味着当前频率仍然是频率为5的TreeNode
,之前仍为null
。根据您的代码,这将导致链接列表创建一个新头,并覆盖前一个。
简而言之,如果插入频率的TreeNode小于磁头的频率,则无法正确分配。要纠正这个问题,应该在while循环之后添加这样的东西:
if(current == head) {
newNode = new TreeNode(newFreq);
newNode.next = head;
head = newNode;
}
另外,在&#34; else&#34;部分如果您的if / else语句,您没有分配&#34; next&#34; newNode
的字段,因此应添加此声明:
newNode.next = current;