【发布时间】:2010-04-24 09:41:06
【问题描述】:
我有一个简单的链表。该节点包含一个字符串(值)和一个整数(计数)。
在我插入时,我需要在链表中按字母顺序插入新节点。如果列表中存在具有相同值的节点,那么我只是增加节点的计数。
我觉得我的方法真的搞砸了。
public void addToList(Node node){
//check if list is empty, if so insert at head
if(count == 0 ){
head = node;
head.setNext(null);
count++;
}
else{
Node temp = head;
for(int i=0; i<count; i++){
//if value is greater, insert after
if(node.getItem().getValue().compareTo(temp.getItem().getValue()) > 0){
node.setNext(temp.getNext());
temp.setNext(node);
}
//if value is equal just increment the counter
else if(node.getItem().getValue().compareTo(temp.getItem().getValue()) == 0){
temp.getItem().setCount(temp.getItem().getCount() + 1);
}
//else insert before
else{
node.setNext(temp);
}
}
}
}
好的,这是插入我所有的字符串,但不是按字母顺序。有没有发现错误?
public Node findIsertionPoint(Node head, Node node){
if( head == null)
return null;
Node curr = head;
while( curr != null){
if( curr.getValue().compareTo(node.getValue()) == 0)
return curr;
else if( curr.getNext() == null || curr.getNext().getValue().compareTo(node.getValue()) > 0)
return curr;
else
curr = curr.getNext();
}
return null;
}
public void insert(Node node){
Node newNode = node;
Node insertPoint = this.findIsertionPoint(this.head, node);
if( insertPoint == null)
this.head = newNode;
else{
if( insertPoint.getValue().compareTo(node.getValue()) == 0)
insertPoint.getItem().incrementCount();
else{
newNode.setNext(insertPoint.getNext());
insertPoint.setNext(newNode);
}
}
count++;
}
【问题讨论】:
-
@user69:我看到您已将我的伪代码改编为 Java。到目前为止做得很好,但是由于某种原因,当
head不是null并且插入的值小于head的值时,您仍然忽略了在head之前插入的逻辑。请再次查看我的伪代码。如果你不明白,问。一切都在那里是有原因的。
标签: java insert linked-list