插入有序链表 - Java ADT

时间:2021-01-10 07:16:26

Hi this is my code for inserting an item...i was told it failed when inserting at the beginning of the list but don't understand why or how to fix it.

嗨这是我的插入项目的代码...我被告知它在列表的开头插入时失败,但不明白为什么或如何解决它。

public void put(K key, V value){
    OrderedLinkedListEntry <K,V> item = new OrderedLinkedListEntry (key, value);

    OrderedLinkedListEntry <K,V> current = head;
    OrderedLinkedListEntry <K,V> previous = null;

    if(current == null){
        head = item;
        numItems ++;
        return;
    }

    while(current != null){
        int result = key.compareTo(current.getKey());
        if(result == 0){
            current.setValue(value);
            return;
        }else if (result < 0){
                  item.setNext(current);
                  if (previous != null){
                  previous.setNext(item);
                  }
                  numItems ++;
                  return;
              }

        previous = current;
        current = current.getNext();

    }

1 个解决方案

#1


0  

In your solution, previous is null when the key to insert is less than the key in the head item.

在您的解决方案中,当插入的键小于head项中的键时,previous为null。

Make a special case for the new key being less than the key in the head:

为新密钥设置一个特殊情况,该密钥小于头部中的密钥:

if (key.compareTo(head.getKey() < 0) {
   item.setNext(head);
   head = item;
   return;
}

You also need to handle the case in which the key is larger than the one in the last item (the result > 0 case).

您还需要处理密钥大于最后一项中的密钥的情况(结果> 0的情况)。

#1


0  

In your solution, previous is null when the key to insert is less than the key in the head item.

在您的解决方案中,当插入的键小于head项中的键时,previous为null。

Make a special case for the new key being less than the key in the head:

为新密钥设置一个特殊情况,该密钥小于头部中的密钥:

if (key.compareTo(head.getKey() < 0) {
   item.setNext(head);
   head = item;
   return;
}

You also need to handle the case in which the key is larger than the one in the last item (the result > 0 case).

您还需要处理密钥大于最后一项中的密钥的情况(结果> 0的情况)。