-2

我是java,我正在尝试实现从双链表中删除的方法,但我很挣扎,不知道如何推进。该方法删除存储在列表中给定节点的数据。我已经读到我需要考虑被删除的元素是开始或结束的情况,但我不知道该怎么做。一般来说,我不确定这是否是正确的方法。我的代码/进度发布在下面。如果有任何帮助,将不胜感激。谢谢

PS我在班级中有一个开始和一个结束参考以及一个尺寸参考

 public type removeAtTheIndex(int index) 
  {
     type theData = null;
    Node <type> current= start;
    Node temp= new Node();
    if (index >= 0 && index < size && start !=null)
    {

        for (int i=0; i < index && current.getNext()!= null; i++)
        {
            current=current.getNext();
        }
        if (current != null)
        {
        if (current == start)
        {

        }

        else if (current == end)
        {

         }

        else
        {
            theData= current.getData();
            temp= current.getPrev();
            temp.setNext(current.getNext());
            current.getNext().setPrev(temp);
            current.setData(null);
            size--;

        }

    }

    return theData;
}
4

1 回答 1

1

我已将type. Type在 Java 中不推荐使用小写的类名。我已经添加了大量的评论,希望你能理解发生了什么。

请注意,这不是经过测试的代码。您可能会在其中发现错误,但我相信流程的本质就在那里。

public Type removeAtTheIndex(int index) {
  // I want to return the data that was removed.
  Type theData = null;
  // Sanity checks.
  if (index >= 0 && index < size && start != null) {
    // Find the entry with the specified index.
    Node<Type> current = start;
    for (int i = 0; i < index && (current = current.getNext()) != null; i++) {
    }
    // Did we find it?
    if (current != null) {
      // Yes! Gather the contents.
      theData = current.getData();
      // Clear it.
      current.setData(null);
      // Special?
      if (current == start) {
        // Its the start one.
        start = start.getNext();
        // Detach it.
        start.setPrev(null);
      } else if (current == end) {
        // Step end back one.
        end = end.getPrev();
        // Detach it.
        end.setNext(null);
      } else {
        // Remove from within list.
        Node prev = current.getPrev();
        // Point it at my next.
        prev.setNext(current.getNext());
        // Point my next to new prev.
        current.getNext().setPrev(prev);
      }
      // One less now.
      size--;
    }
  }
  return theData;
}
于 2012-11-14T10:11:25.227 回答