簡體   English   中英

從單鏈表中刪除兩個給定位置之間的節點?

[英]Removing nodes between two given positions from 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;
}

刪除單鏈表上兩個節點之間的所有節點並不是很難。

你需要兩個占位符。 您將遍歷鏈接列表,直到找到起始節點,並將其中一個占位符設置為等於它。 然后,將第二個占位符移動到鏈接列表的其余部分,直到找到第二個節點。 設置您的第一個節點 - >下一個參數等於第二個節點,並且您已經有效地刪除了它們之間的所有內容。

為了正確清理,您應該跟蹤第一個節點之后的下一個節點,並釋放從內存中刪除的所有節點,但這在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;
    }
}  

您只需將刪除范圍開始處的節點的下一個指針設置為刪除范圍結束時的節點。 由於沒有對刪除范圍中的節點的引用,Java的垃圾收集應該清除它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM