从单链表中删除两个给定位置之间的节点?

时间:2014-04-23 20:05:07

标签: java singly-linked-list

我正在自学数据结构,并关注这个主题的Java书籍。目前我正在学习Linked List的实现。我一直在努力学习如何编写一个采用“startPos”和“endPos”的方法,并相应地删除节点。我正在验证“startPos”和“endPos”以捕获无效的位置输入。我已经谷歌搜索方向,但没有遇到任何可以帮助我顺应这个逻辑的在线示例。我非常感谢您的任何指导。谢谢。

class Node{

   public Object data;
   public Node next;

}

删除节点方法

  public void deleteNodes( int startPos, int endPos ){         
      Node node = _nHead;
      int counter = 0;

  if( startPos < 1 || startPos > getSize() )
      return;

  if( endPos < 1 || endPos > getSize() ) 
      return;


  while( node != null){

    node = node.next;
    ++counter;
  }
}   

获得大小

public int getSize(){

    int counter = 0;

    for( Node node = _nHead; node != null; node = node.next )
    ++counter;
    return counter;
}

2 个答案:

答案 0 :(得分:2)

删除单链表上两个节点之间的所有节点并不是很难。

您需要两个占位符。您将遍历链接列表,直到找到起始节点,并将其中一个占位符设置为等于它。然后,将第二个占位符移动到链接列表的其余部分,直到找到第二个节点。设置您的第一个节点 - &gt;下一个参数等于第二个节点,并且您已经有效地删除了其中的所有内容。

为了正确清理,您应该跟踪第一个节点之后的下一个节点并释放从内存中删除的所有节点,但这在C中比Java更重要。

对于双向链表,该方法类似,除了您还必须在第一个节点之前设置第二个节点。

举个例子:

public void deleteNodes( int startPos, int endPos ){         
    Node node = _nHead;
    Node start;
    Node end;

    int counter = 0;

    if( startPos < 1 || startPos > getSize() )
        return;

    if( endPos < 1 || endPos > getSize() ) 
        return;

    if (endPos < startPos)
    {
        int placeholder = startPos;
        startPos = endPos;
        endPos = placeholder;   // switches end and start if start is greater than end
    }

    if (endPos == startPos)
        return; // if they are equal we aren't deleting anything;


    while( node != null)
    {
        if (counter == startPos)
            start = node;

        if (counter == endPos)
            end = node;

        node = node.next;
        counter++;
    }

    if (start != NULL && end != NULL)
    {
        start.next = end;
    }
}  

答案 1 :(得分:0)

您只需将删除范围开始处的节点的下一个指针设置为删除范围结束时的节点。由于没有对删除范围中的节点的引用,Java的垃圾收集应该清除它们。

相关问题