从双链表中删除

时间:2012-11-14 08:52:03

标签: java android

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

P.S。我在类中有一个开始和结束引用以及一个大小引用

 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;
}

1 个答案:

答案 0 :(得分: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;
}