簡體   English   中英

如何使用此功能擺脫Java中單個鏈接列表中的節點?

[英]How to get rid of a node in a single linked list in java with this function?

我有一個名為findNode的函數,該函數接收數據並返回鏈表中的節點。

//helper function that finds the nodes
    private ListNode findNode(E toFind){

        ListNode current = front;

        while(current!=null){

            if(toFind.equals(current.data)){
                return current; 
            }
            else{
                current = current.next;
            }


        }

        return null;

    }

我將如何使用它刪除節點?

您可以嘗試如下操作:
查找next值為查找結果的NodeNode ,然后更新這些節點之間的鏈接,例如:

//iterate over List
  if(current.next = resultOfFindNode){
    //exit loop
  }
//outside of loop
current.setNext(resultOfFindNode.next);

基於findNode編寫一個名為findPrevNode的函數,您可以使用該函數從列表中刪除該節點,如下所示。

ListNode deleteNode;
if (toFind.equals(front.next.data)) {
   // Found at the front of the list, no prev pointer
   deleteNode = front;
   front = front.next;
}
else if ((prev = findPrevNode(toFind)) != NULL) {
  // Found after the start of the list
  deleteNode = prev.next;
  prev.next = prev.next.next;
}
else {} // Not found

findPrevNode看起來像這樣:

private ListNode findPrevNode(E toFind){

    ListNode current = front;
    if (current == NULL) return NULL;

    while(current.next != null){
        if(toFind.equals(current.next.data)){
            return current; 
        }

        current = current.next;
    }

    return null;
}

暫無
暫無

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

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