【问题标题】:Delete last element in singleLinked List删除单链表中的最后一个元素
【发布时间】:2015-06-29 06:44:54
【问题描述】:

我正在制作一个简单的链表,我正在尝试实现一种方法,该方法允许我删除链表的最后一个节点。在某些时候,我的方法是错误的,我不确定错误在哪里以及如何修复它。这是代码!

public Nodo deleteEnd() {

    Nodo aux;
    if (head == null) {
        throw new NoSuchElementException("Element cant be deleted");

    } else {

        aux = head;

        while (aux.next.next != null) {
            aux = aux.next;
        }

        size--;
    }
    return aux;
}

【问题讨论】:

    标签: java methods nodes singly-linked-list


    【解决方案1】:

    尝试减少一个.next

        while (aux.next != null) {
            aux = aux.next;
        }
    

    【讨论】:

    • 似乎是一样的,我在 Java 中很新,所以我不知道我是否以正确的方式接近解决方案。
    【解决方案2】:

    添加

    aux.next = null;
    

    在 while 循环之后 - 将不会引用最后一个元素。

    【讨论】:

      【解决方案3】:
      public Nodo deleteEnd() {
          if (head == null) {
              throw new NoSuchElementException("Element can't be deleted");
          }
          Nodo current = head;
          Nodo next = current.next;
      
          // Check if there is only the head element.
          if ( next == null )
          {
              size--;
              head = null;
              return current;
          }
      
          // Skip to the end.
          while (next.next != null) {
              current = next;
              next = next.next;
          }
      
          // Break the link to the next element.
          current.next = null;
          size--;
          return next;
      }
      

      【讨论】:

        【解决方案4】:

        您需要将最后一个但并非最不重要的节点的next 分配给null

        if(head.next == null) {
            // head is last!
            head = null;
            size = 0;
        } else {
            previous = head;
            current = head.next;
            // while current is not last, keep going
            while(current.next != null) {
               previous = current;
               current = current.next;
            }
            // current is now on last!
            previous.next = null;
            size--;
        }
        

        【讨论】:

        • 非常感谢您的帮助!我很欣赏它:)
        猜你喜欢
        • 1970-01-01
        • 2017-01-04
        • 2014-12-08
        • 2019-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-09
        相关资源
        最近更新 更多