简体   繁体   中英

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

I have a function called findNode that takes in the data and returns the node in a linked list.

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

    }

How would I use this to remove a node?

You can try something like this:
Find Node whose next value is Node that was result of find then update link between these nodes such as:

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

Write a function called findPrevNode based on findNode that you can use to delete the node from the list, like this.

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 would look something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM