Linked List: Delete a specific node

Question: Write a function that deletes the node passed as a parameter

    //method to delete the last node of the linked list
    public void delete(ListNode node){

        //throw exception if the list is empty
        if(head==null){
            return;
        }

        //if the node passed is the head node then change the head pointer to the next node
        else if(node==head){
            System.out.println(head.getData() + " deleted");
            head= head.getNext();
        }

        else {
            //pointer temp which will traverse the linked list
            ListNode temp= head;

            //find the node which points to the node to be deleted
            while (temp.getNext()!=node && temp!=null){
              temp=temp.getNext();
            }

            //if node if found then delete the node otherwise return
            if (temp!=null){
                System.out.println(temp.getNext().getData() + " deleted");
                temp.setNext(node.getNext());
            } else {
                return;
            }

        }
    }

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: