插入有序链表 - Java ADT

发布于 2024-10-24 06:56:02 字数 891 浏览 1 评论 0原文

您好,这是我用于插入项目的代码...我被告知在列表开头插入时失败,但不明白为什么或如何修复它。

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();

    }

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();

    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

幸福还没到 2024-10-31 06:56:02

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

为新键小于头部键的特殊情况:

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

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

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

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文