简体   繁体   中英

Remove a n number of nodes after a p node (Java) in Doubly Linked List

public void removeNNodes(Node<E> p, int n){
        for(Node<E> j =first; j!= null ; j=j.next ){
                if(j==p){ 
                   deleteNode(j.next);
                   current--;
                   n--; 
                }
        }
    }

i´m trying to get to delete the nodes that come after the p node an number of nodes after the p node and keep it in 0(n)

Your logic isn't correct. As written, you are only ever deleting p, iff it exists in the list. What you need is to go n steps forward from p, and then connect that node as next in p, like

  public void removeNNodes(Node<E> p, int n){
    if (i <= 0 ) throw new IllegalArgumentException(...);
    Node<E> next = p.next;
    while (; n > 1; i--) {  //n>1 because we've already gotten the next one on the line above
      if (next == null) {
        throw new NoSuchElementException(...);
      } else {
        next = next.next;
      }
    }
    //now you just need to set p.next to next, and next.prev to p (if next isn't null) 
}

This is one of the beautiful things about linkedlists: You can snip out a whole string of nodes by just setting 1 (2 for doubly linked) "pointers"

first of all, i'd recomend using a while-loop instead of a for-loop, since with a while loop, you can control what the next node becomes (you'll see why in a sec)

This is how I would approch this:

public void removeNNodes(Node<E> p, int n){
    int counter = 0; //count the number of time a node was deleted
    boolean encounter = false; //flag to check when the p-node has been 
                                //encounterd
    
    Node<E> curr = first; //iterator node set to the first node
    while(curr != NULL){
        if(curr == p){
            encounter = true; //p-node has been encountered
            continue; //since we don't want to delete the p-node
        }
        if(encounter && counter <= n){ //if the node is after the p-node and 
                                       // and the node delete counter is less
                                       // than n
            Node <E> temp = curr.next;
            deleteNode(curr);
            current--;
            counter++;
            curr = temp; //go to next node
            continue;
        }
        curr = curr.next;
    }
}

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