Java Linked List search and delete method

后端 未结 3 1850
谎友^
谎友^ 2020-12-07 00:05

I have a project for computer science class and have everything done except for one method. The delete method. Basically I am making a linked list from user input and I need

相关标签:
3条回答
  • 2020-12-07 00:08

    All you need to do is search through the list, keeping track of where you are. When the node you want to delete is in front of you, set the current node's "next" to the one after the one you want to delete:

    for(Node current = list; current.next() != null; current = current.next()){
       if(current.next().magazine().equals(toDelete)) current.setNext(current.next().next());
    }
    

    Something like that. Hope that helps!

    0 讨论(0)
  • 2020-12-07 00:20

    Without spoon feeding you the answer. deletion is a bit like removing one link of a chain - you cut out the link and join up the two (new) ends.

    So, deleting "B" would mean changing

    A --> B --> C --> D
    

    to this

    A --> C --> D
    


    In pseudo code, the algorithm would be:

    • start the algorithm with the first node
    • check if it is the one you want to delete
    • if not, go to the next node and check again (go back to the previous step)
    • if so, make the next node of the previous node the next node of this node
    • remove the reference from this node to the next node
    0 讨论(0)
  • 2020-12-07 00:31
    public void delete (Magazine mag) {
        MagazineNode current = this.list;
        MagazineNode before;
    
        //if is the first element
        if (current.equals(mag)) {
            this.list = current.next;
            return;     //ending the method
        }
    
    
        before = current;
    
        //while there are elements in the list
        while ((current = current.next) != null) {
    
            //if is the current element
            if (current.equals(mag)) {
                before.next = current.next;
                return;     //endind the method 
            }
    
            before = current;
        }
    
        //it isnt in the list
    }
    

    the comments should explains whats happening

    0 讨论(0)
提交回复
热议问题