【问题标题】:Doubly Linked List Remove Method双向链表删除方法
【发布时间】:2015-12-28 20:18:27
【问题描述】:

尝试实现一种方法,该方法删除指定索引处的节点并返回其数据元素。参加初学者在线课程,但我不确定如何返回数据类型 E。抱歉,如果我的代码很糟糕。

public class MyLinkedList<E> extends AbstractList<E> {
    LLNode<E> head;
    LLNode<E> tail;
    int size;

    /** Create a new empty LinkedList */
    public MyLinkedList() {
        size = 0;
        head = new LLNode<E>(null); 
        tail = new LLNode<E>(null);
        head.next = tail;
        tail.prev = head;

    public E remove(int index) 
    {
        int ithNode = 1; //tracks node path location
        LLNode<E> newNode = new LLNode<E>(null);

        if (index < 0 || index > size()) {
            throw new IndexOutOfBoundsException();
        }

        if (index == 1) {
            newNode = head.next;
            head.next = null;
            head.prev = null;
        } else {
            while (ithNode != index) {
                head = head.next;
                ithNode++;
            }
            if (head.next == null) {
                head.prev.next = null;
                head.prev = null;
            } else {
                head.prev.next = head.next;
                head.next.prev = head.prev;
            }
        }
    }

}

class LLNode<E> 
{
    LLNode<E> prev;
    LLNode<E> next;
    E data;

//Not sure if I should create another constructor here 
    public LLNode(E e) 
    {
        this.data = e;
        this.prev = null;
        this.next = null;
    }
}

【问题讨论】:

  • 如果你删除了一些东西,为什么不返回你删除的节点,或者干脆不返回任何东西
  • if (index &lt; 0 || index &gt; size()) 应该是 if (index &lt; 0 || index &gt;= size()) 或者最好是在删除方法的第 4 行中的 if (!(index &gt;= 0 &amp;&amp; index &lt; size()))
  • 我想我不明白你的任务。为什么要发明自己的课程? java.util.LinkedList 是双向的,并实现了一个 remove() 方法,该方法返回已删除的元素。 docs.oracle.com/javase/7/docs/api/java/util/…

标签: java linked-list doubly-linked-list


【解决方案1】:

请记住,E 是任何数据类型将进入 LinkedList 的占位符。您将像返回任何其他元素一样返回数据。我的建议是一旦你到达要删除的元素,保存那里的数据,设置新的下一个和上一个引用,然后返回数据。示例:

E returnData = head.data;
//set references
return returnData;

【讨论】:

    猜你喜欢
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-27
    • 2018-09-16
    相关资源
    最近更新 更多