Open In App

Program to delete all even nodes from a Singly Linked List

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given a singly linked list containing N nodes, the task is to delete all the even nodes from the list.
 

Examples:  

Input: LL = 1 -> 4 -> 3 -> 18 -> 19 
Output: 1 -> 3 -> 19
Input: LL = 5 -> 3 -> 6 -> 8 -> 4 -> 1 -> 2 -> 9 
Output: 5 -> 3 -> 1 -> 9 
 

Approach 1: 

  • The idea is to traverse the nodes of the singly linked list one by one and get the pointer of the nodes having even data. Delete those nodes by following the approach used in this post.

Below is the implementation of the above idea:
 

C++




// C++ implementation to delete all
// even nodes from the singly linked list
 
#include <bits/stdc++.h>
using namespace std;
 
// Node of the singly linked list
struct Node
{
    int data;
    struct Node* next;
};
 
// Function to insert a node at
// the beginning of the singly
// Linked List
void push(struct Node** head_ref,
          int new_data)
{
    struct Node* new_node
        = (struct Node*)malloc(
            sizeof(
                struct Node));
 
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}
 
// Function to delete a node in a
// singly Linked List.
// head_ref --> Pointer to head
// node pointer.
// key --> Node to be deleted
void deleteNode(struct Node** head_ref,
                int key)
{
    // Store head node
    struct Node *temp = *head_ref,
                *prev;
 
    // If head node itself holds
    // the key to be deleted
    if (temp != NULL
        && temp->data == key) {
        // Changed head
        *head_ref = temp->next;
        return;
    }
 
    // Search for the key to be
    // deleted, keep track of the
    // previous node as we need
    // to change 'prev->next'
    while (temp != NULL
           && temp->data != key) {
        prev = temp;
        temp = temp->next;
    }
 
    // If key was not present
    // in linked list
    if (temp == NULL)
        return;
 
    // Unlink the node from
    // linked list
    prev->next = temp->next;
 
    
}
 
// Function to delete all the
// even nodes from the
// singly linked list
void deleteEvenNodes(Node** head_ref)
{
    Node* ptr = *head_ref;
    // Node* next;
 
    while (ptr != NULL) {
        // next = ptr->next;
        // If true, delete node 'ptr'
        if (ptr->data % 2 == 0)
            deleteNode(head_ref,
                       ptr->data);
        ptr = ptr->next;
    }
}
 
// This function prints contents
// of linked list starting from
// the given node
void printList(struct Node* node)
{
    while (node != NULL) {
        printf(" %d -> ", node->data);
        node = node->next;
    }
}
 
// Driver code
int main()
{
    // Start with the empty list
    Node* head = NULL;
    push(&head, 19);
    push(&head, 18);
    push(&head, 3);
    push(&head, 4);
    push(&head, 1);
 
    printf("Initial List: ");
    printList(head);
 
    deleteEvenNodes(&head);
 
    printf("\nFinal List: ");
    printList(head);
}


Java




// Java implementation to delete all
// even nodes from the singly linked list
class LinkedList{
     
// head of list
Node head;
 
// Linked list Node
class Node
{
    int data;
    Node next;
    Node(int d)
    {
        data = d;
        next = null;
    }
}
 
// Function to insert a node at
// the beginning of the singly
// Linked List
public void push(int new_data)
{
    Node new_node = new Node(new_data);
    new_node.next = head;
    head = new_node;
}
 
// Function to delete a node in a
// singly Linked List.
void deleteNode(int key)
{
     
    // Store head node
    Node temp = head, prev = null;
 
    // If head node itself holds the
    // key to be deleted
    if (temp != null && temp.data == key)
    {
         
        // Changed head
        head = temp.next;
        return;
    }
 
    // Search for the key to be deleted,
    // keep track of the previous node
    // as we need to change temp.next
    while (temp != null && temp.data != key)
    {
        prev = temp;
        temp = temp.next;
    }
 
    // If key was not present in linked list
    if (temp == null) return;
 
    // Unlink the node from linked list
    prev.next = temp.next;
}
 
// Function to delete all the nodes
// from linked list containing
// even numbers.
void deleteEvenNodes()
{
    Node ptr = head;
 
    // loop to iterate the linked list
    while(ptr != null)
    {
 
        // If containing element is even
        if(ptr.data % 2 == 0)
        {
             
            // Delete the node
            deleteNode(ptr.data);
        }
        ptr = ptr.next;
    }
}
 
// This function prints contents of linked
// list starting from the given node
public void printList()
{
    Node ptr = head;
    while (ptr != null)
    {
        System.out.print(ptr.data + "-> ");
        ptr = ptr.next;
    }
}
 
// Driver code
public static void main(String[] args)
{
    LinkedList head = new LinkedList();
 
    head.push(19);
    head.push(18);
    head.push(3);
    head.push(4);
    head.push(1);
 
    System.out.print("\nInitial List: ");
    head.printList();
 
    head.deleteEvenNodes();
 
    System.out.print("\nFinal List: ");
    head.printList();
}
}
 
// This code is contributed by Amit Mangal


Python3




# Python3 implementation to delete all
# even nodes from the singly linked list
# Node class
class Node:
     
    # Function to initialize the node object
    def __init__(self, data):
         
        # Assign data
        self.data = data
         
        # Initialize
        # next as null
        self.next = None
     
# Linked List Class
class LinkedList:
     
    # Function to initialize the
    # LinkedList class.
    def __init__(self):
 
        # Initialize head as None
        self.head = None
 
    # This function insert a new node at
    # the beginning of the linked list
    def push(self, new_data):
     
        # Create a new Node
        new_node = Node(new_data)
 
        # Make next of new Node as head
        new_node.next = self.head
 
        # Move the head to point to new Node
        self.head = new_node
         
    # Method to print the linked list
    def printList(self):
 
        # Object to iterate
        # the list
        ptr = self.head
 
        # Loop to iterate list
        while(ptr != None):
             
            print(ptr.data, '-> ', end = '')
 
            # Moving the iterating object
            # to next node
            ptr = ptr.next
             
        print()
 
    # Method to delete a node in
    # a singly linked list.
    def deleteNode(self, key):
        temp = self.head
 
        # If head node itself holds
        # the key to be deleted.
        if(temp != None and temp.data == key):
 
            # Changing head of list.
            self.head = temp.next
            return
 
        # Search for the key to be
        # deleted, keep track of the
        # previous node as we need
        # to change prev.next
        while(temp != None and temp.data != key):
            prev = temp
            temp = temp.next
 
        # If is not present in list
        if(temp == None):
            return
 
        # Unlink the node from
        # linked list
        prev.next = temp.next
 
    # Method to delete all the
    # even nodes from singly
    # linked list.
    def deleteEvenNodes(self):
        ptr = self.head
 
        # Loop to iterate the
        # linked list.
        while(ptr != None):
 
            # If node contains even number.
            if(ptr.data % 2 == 0):
 
                # Deleting the node
                self.deleteNode(ptr.data)
                 
            ptr = ptr.next
 
# Driver code
if __name__=='__main__':
 
    head = LinkedList()
     
    # Pushing elements at start
    # of linked list.
    head.push(19)
    head.push(18)
    head.push(3)
    head.push(4)
    head.push(1)
     
    # Print initial linked list
    print("Initial list: ", end = '')
    head.printList()
 
    # Calling the function to delete
    # nodes containing even numbers.
    head.deleteEvenNodes()
 
    # Print the final list
    print("Final list: ", end = '')
    head.printList()
     
# This code is contributed by Amit Mangal


C#




// C# implementation to delete all
// even nodes from the singly linked list
using System;
class List{
 
  // head of list
  Node head;
 
  // Linked list Node
  public class Node
  {
    public int data;
    public Node next;
    public Node(int d)
    {
      data = d;
      next = null;
    }
  }
 
  // Function to insert a node at
  // the beginning of the singly
  // Linked List
  public void push(int new_data)
  {
    Node new_node = new Node(new_data);
    new_node.next = head;
    head = new_node;
  }
 
  // Function to delete a node in a
  // singly Linked List.
  void deleteNode(int key)
  {    
    // Store head node
    Node temp = head, prev = null;
 
    // If head node itself holds the
    // key to be deleted
    if (temp != null &&
        temp.data == key)
    {        
      // Changed head
      head = temp.next;
      return;
    }
 
    // Search for the key to be deleted,
    // keep track of the previous node
    // as we need to change temp.next
    while (temp != null &&
           temp.data != key)
    {
      prev = temp;
      temp = temp.next;
    }
 
    // If key was not present
    // in linked list
    if (temp == null)
      return;
 
    // Unlink the node from
    // linked list
    prev.next = temp.next;
  }
 
  // Function to delete
  // all the nodes  from
  // linked list containing
  // even numbers.
  void deleteEvenNodes()
  {
    Node ptr = head;
 
    // loop to iterate the linked list
    while(ptr != null)
    {
      // If containing element is even
      if(ptr.data % 2 == 0)
      {            
        // Delete the node
        deleteNode(ptr.data);
      }
      ptr = ptr.next;
    }
  }
 
  // This function prints contents of linked
  // list starting from the given node
  public void printList()
  {
    Node ptr = head;
    while (ptr != null)
    {
      Console.Write(ptr.data + "-> ");
      ptr = ptr.next;
    }
  }
 
  // Driver code
  public static void Main(String []args)
  {
    List head = new List();
 
    head.push(19);
    head.push(18);
    head.push(3);
    head.push(4);
    head.push(1);
 
    Console.Write("\nInitial List: ");
    head.printList();
 
    head.deleteEvenNodes();
 
    Console.Write("\nFinal List: ");
    head.printList();
  }
}
  
// This code contributed by gauravrajput1


Javascript




<script>
// javascript implementation to delete all
// even nodes from the singly linked list
 
    // head of list
    var head;
 
    // Linked list Node
     class Node {
            constructor(val) {
                this.data = val;
                this.next = null;
            }
        }
 
    // Function to insert a node at
    // the beginning of the singly
    // Linked List
     function push(new_data) {
var new_node = new Node(new_data);
        new_node.next = head;
        head = new_node;
    }
 
    // Function to delete a node in a
    // singly Linked List.
    function deleteNode(key) {
 
        // Store head node
var temp = head, prev = null;
 
        // If head node itself holds the
        // key to be deleted
        if (temp != null && temp.data == key) {
 
            // Changed head
            head = temp.next;
            return;
        }
 
        // Search for the key to be deleted,
        // keep track of the previous node
        // as we need to change temp.next
        while (temp != null && temp.data != key) {
            prev = temp;
            temp = temp.next;
        }
 
        // If key was not present in linked list
        if (temp == null)
            return;
 
        // Unlink the node from linked list
        prev.next = temp.next;
    }
 
    // Function to delete all the nodes
    // from linked list containing
    // even numbers.
    function deleteEvenNodes() {
var ptr = head;
 
        // loop to iterate the linked list
        while (ptr != null) {
 
            // If containing element is even
            if (ptr.data % 2 == 0) {
 
                // Delete the node
                deleteNode(ptr.data);
            }
            ptr = ptr.next;
        }
    }
 
    // This function prints contents of linked
    // list starting from the given node
     function printList() {
var ptr = head;
        while (ptr != null) {
            document.write(ptr.data + "-> ");
            ptr = ptr.next;
        }
    }
 
    // Driver code
     
 
        push(19);
        push(18);
        push(3);
        push(4);
        push(1);
 
        document.write("<br/>Initial List: ");
        printList();
 
        deleteEvenNodes();
 
        document.write("<br/>Final List: ");
        printList();
 
// This code contributed by aashish1995
</script>


Output

Initial List:  1 ->  4 ->  3 ->  18 ->  19 -> 
Final List:  1 ->  3 ->  19 -> 






Time Complexity: O(N^2)

As the complexity of deleteNode function is O(N) and we need to call it for every even number.  

Auxiliary Space: O(1)

As constant extra space is used.

Approach 2:

The idea is to traverse the linked list one by one and get the pointer of nodes having even values. Also keep deleting the nodes having even values using the method used in this post.

We want the time complexity to be O(1) for deleting a given node in order to get O(N) solution for overall approach.

The algorithm for the deleteNode function:

  1. In the deleteNode function we get the pointer  of the node to be deleted directly.
  2. Copy the value of next node’s to this node.
  3. delete the next node.

The only thing to keep in mind is that the node to be deleted should not be the last node if we are using the above method to delete the node, but it gives the result in O(1) time so we will use this in our solution.

The algorithm for the deleteEvenNodes function:

  1. We get the head of the linked list as a function parameter.
  2. Use dummy pointer variables ptr and prev which are used to store the current and previous node respectively.
  3. Traverse the linked list before last element using a while loop and do the following:
  4.     delete the nodes with odd values and keep updating the prev and ptr pointers
  5. The case of last node is handled explicitly at the end.

Full implementation of above approach:

C++




// C++ implementation to delete all
// even valued nodes from the singly linked list
 
#include <bits/stdc++.h>
using namespace std;
 
// Node of the singly linked list
struct Node {
    int data;
    struct Node* next;
};
 
// Function to insert a node at
// the beginning of the singly
// Linked List
void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node
        = (struct Node*)malloc(sizeof(struct Node));
 
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}
 
// Function to delete a node in a
// singly Linked List.
// node --> Pointer to given node
void deleteNode(struct Node* node)
{
    // copy the next node's value in current node
    node->data = node->next->data;
    // store the pointer to node's next in a temp variable
    struct Node* temp = node->next;
    // connect the node with node's next's next
    node->next = node->next->next;
    // delete the temp
    delete (temp);
}
 
// Function to delete all the
// even valued nodes from the
// singly linked list
void deleteEvenNodes(Node** head_ref)
{
    Node* ptr = *head_ref;
    Node* prev;
    // mark the current head with ptr pointer
 
    while (ptr != NULL && ptr->next != NULL) {
        // traverse the linked list before the last element
        if (ptr->data % 2 == 0)
            deleteNode(ptr);
        // delete the node if the value of the node is even
        else {
            prev = ptr;
            ptr = ptr->next;
        }
        // move the pointer to the next element and store
        // the prev node
    }
    if (ptr == *head_ref && ptr->data % 2 == 0)
        *head_ref = NULL;
    else if (ptr->data % 2 == 0) {
        prev->next = NULL;
        delete ptr;
    }
}
 
// This function prints contents
// of linked list starting from
// the given node
void printList(struct Node* node)
{
    while (node != NULL) {
        printf(" %d -> ", node->data);
        node = node->next;
    }
}
 
// Driver code
int main()
{
    // Start with the empty list
    Node* head = NULL;
    push(&head, 2);
    push(&head, 6);
    push(&head, 15);
    push(&head, 16);
    push(&head, 18);
 
    printf("Initial List: ");
    printList(head);
 
    deleteEvenNodes(&head);
 
    printf("\nFinal List: ");
    printList(head);
}
 
// This code was contributed by Abhijeet Kumar


Java




// Java implementation to delete all
// even valued nodes from the singly linked list
class LinkedList{
     
// head of list
Node head;
 
// Linked list Node
class Node
{
    int data;
    Node next;
    Node(int d)
    {
        data = d;
        next = null;
    }
}
 
// Function to insert a node at
// the beginning of the singly
// Linked List
public void push(int new_data)
{
    Node new_node = new Node(new_data);
    new_node.next = head;
    head = new_node;
}
 
// Function to delete a node in a
// singly Linked List.
void deleteNode(Node node)
{
    // copy the next node's value in current node
    node.data = node.next.data;
     
    // connect the node with node's next's next
    node.next = node.next.next;
}
 
// Function to delete all the nodes
// from linked list containing
// even numbers.
void deleteEvenNodes()
{
    Node ptr = head;
    Node prev = null;
    //mark the current head with ptr pointer
 
    while (ptr!=null && ptr.next != null)
    {
        // traverse the linked list before the last element
        if (ptr.data % 2 == 0)
            deleteNode(ptr);
        // delete the node if the value of the node is even
        else{
        prev = ptr;
        ptr = ptr.next;
        }
        // move the pointer to the next element and store the previous pointer
    }
    if(ptr==head && ptr.data % 2 == 0)
      head = null;
    else if(ptr.data % 2 == 0)
    prev.next = null;
}
 
// This function prints contents of linked
// list starting from the given node
public void printList()
{
    Node ptr = head;
    while (ptr != null)
    {
        System.out.print(ptr.data + "-> ");
        ptr = ptr.next;
    }
}
 
// Driver code
public static void main(String[] args)
{
    LinkedList head = new LinkedList();
 
    head.push(2);
    head.push(6);
    head.push(15);
    head.push(16);
    head.push(18);
 
    System.out.print("\nInitial List: ");
    head.printList();
 
    head.deleteEvenNodes();
 
    System.out.print("\nFinal List: ");
    head.printList();
}
}
 
// This code is contributed by Abhijeet Kumar(abhijeet19403)


Python3




# Python3 implementation to delete all
# even valued nodes from the singly linked list
 
# Node class
class Node:
     
    # Function to initialize the node object
    def __init__(self, data):
         
        # Assign data
        self.data = data
         
        # Initialize
        # next as null
        self.next = None
     
# Linked List Class
class LinkedList:
     
    # Function to initialize the
    # LinkedList class.
    def __init__(self):
 
        # Initialize head as None
        self.head = None
 
    # This function insert a new node at
    # the beginning of the linked list
    def push(self, new_data):
     
        # Create a new Node
        new_node = Node(new_data)
 
        # Make next of new Node as head
        new_node.next = self.head
 
        # Move the head to point to new Node
        self.head = new_node
         
    # Method to print the linked list
    def printList(self):
 
        # Object to iterate
        # the list
        ptr = self.head
 
        # Loop to iterate list
        while(ptr != None):
             
            print(ptr.data, '-> ', end = '')
 
            # Moving the iterating object
            # to next node
            ptr = ptr.next
             
        print()
 
    # Method to delete a node in
    # a singly linked list.
    def deleteNode(self,node):
        # copy the next node's value in current node
        node.data = node.next.data
     
        # connect the node with node's next's next
        node.next = node.next.next
 
    # Method to delete all the
    # even valued nodes from singly
    # linked list.
    def deleteEvenNodes(self):
          #mark the current head with ptr pointer
        ptr = self.head
        prev = self.head
         
        # traverse the linked list before the last element
        while (ptr!=None and ptr.next != None):
            # delete the node if the value of the node is even
            if (ptr.data % 2 == 0):
                self.deleteNode(ptr)
            # move the pointer to the next element and store the previous pointer
            else:
                prev = ptr
                ptr = ptr.next
            
        if(ptr==self.head and ptr.data % 2 == 0):
            head = None
        elif(ptr.data % 2 == 0):
            prev.next = None
 
# Driver code
if __name__=='__main__':
 
    head = LinkedList()
     
    # Pushing elements at start
    # of linked list.
    head.push(18)
    head.push(16)
    head.push(15)
    head.push(6)
    head.push(2)
     
    # Print initial linked list
    print("Initial list: ", end = '')
    head.printList()
 
    # Calling the function to delete
    # nodes containing even numbers.
    head.deleteEvenNodes()
 
    # Print the final list
    print("Final list: ", end = '')
    head.printList()
     
# This code is contributed by Abhijeet Kumar(abhijeet19403)


C#




// C# implementation to delete all
// even valued nodes from the singly linked list
using System;
class List{
 
  // head of list
  Node head;
 
  // Linked list Node
  public class Node
  {
    public int data;
    public Node next;
    public Node(int d)
    {
      data = d;
      next = null;
    }
  }
 
  // Function to insert a node at
  // the beginning of the singly
  // Linked List
  public void push(int new_data)
  {
    Node new_node = new Node(new_data);
    new_node.next = head;
    head = new_node;
  }
 
  // Function to delete a node in a
  // singly Linked List.
  void deleteNode(Node node)
  {    
   // copy the next node's value in current node
    node.data = node.next.data;
     
    // connect the node with node's next's next
    node.next = node.next.next;
  }
 
  // Function to delete
  // all the nodes  from
  // linked list containing
  // even numbers.
  void deleteEvenNodes()
  {
     Node ptr = head;
     Node prev = null;
     //mark the current head with ptr pointer
 
     while (ptr!=null && ptr.next != null)
     {
        // traverse the linked list before the last element
        if (ptr.data % 2 == 0)
            deleteNode(ptr);
        // delete the node if the value of the node is even
        else{
        prev = ptr;
        ptr = ptr.next;
        }
        // move the pointer to the next element and store the previous pointer
     }
     if(ptr==head && ptr.data % 2 == 0)
       head = null;
     else if(ptr.data % 2 == 0)
     prev.next = null;
  }
 
  // This function prints contents of linked
  // list starting from the given node
  public void printList()
  {
    Node ptr = head;
    while (ptr != null)
    {
      Console.Write(ptr.data + "-> ");
      ptr = ptr.next;
    }
  }
 
  // Driver code
  public static void Main(String []args)
  {
    List head = new List();
 
    head.push(2);
    head.push(6);
    head.push(15);
    head.push(16);
    head.push(18);
 
    Console.Write("\nInitial List: ");
    head.printList();
 
    head.deleteEvenNodes();
 
    Console.Write("\nFinal List: ");
    head.printList();
  }
}
  
// This code contributed by Abhijeet Kumar(abhijeet19403)


Javascript




<script>
// javascript implementation to delete all
// even nodes from the singly linked list
 
    // head of list
    var head;
 
    // Linked list Node
     class Node {
            constructor(val) {
                this.data = val;
                this.next = null;
            }
        }
         
    // Function to insert a node at
    // the beginning of the singly
    // Linked List
     function push(new_data) {
var new_node = new Node(new_data);
        new_node.next = head;
        head = new_node;
    }
 
    // Function to delete a node in a
    // singly Linked List.
    void deleteNode(Node node)
    {
        // copy the next node's value in current node
        node.data = node.next.data;
         
        // connect the node with node's next's next
        node.next = node.next.next;
    }
 
    // Function to delete all the nodes
    // from linked list containing
    // even numbers.
    function deleteEvenNodes() {
    var ptr = head,prev = null;
    //mark the current head with ptr pointer
 
    while (ptr!=null && ptr.next != null)
    {
        // traverse the linked list before the last element
        if (ptr.data % 2 == 0)
            deleteNode(ptr);
        // delete the node if the value of the node is even
        else{
        prev = ptr;
        ptr = ptr.next;
        }
        // move the pointer to the next element and store the previous pointer
    }
    if(ptr==head && ptr.data % 2 == 0)
      head = null;
    else if(ptr.data % 2 == 0)
    prev.next = null;
    }
 
    // This function prints contents of linked
    // list starting from the given node
     function printList() {
    var ptr = head;
        while (ptr != null) {
            document.write(ptr.data + "-> ");
            ptr = ptr.next;
        }
    }
 
    // Driver code
     
 
        push(2);
        push(6);
        push(15);
        push(16);
        push(18);
 
        document.write("<br/>Initial List: ");
        printList();
 
        deleteEvenNodes();
 
        document.write("<br/>Final List: ");
        printList();
 
// This code contributed by Abhijeet Kumar(abhijeet19403)
</script>


Output

Initial List:  18 ->  16 ->  15 ->  6 ->  2 -> 
Final List:  15 -> 






Time Complexity: O(N)

As we are visiting every node and deleting odd valued node which is O(1) operation.

Auxiliary Space: O(1)

As constant extra space is used.

Recursive Approach:

  • Base Case: If the current node is NULL, return NULL.
  • If the head is null, then return null as the list is empty.
  • If the head’s value is even, then return the next node recursively.
  • If the head’s value is odd, then assign the head’s next to the result of the recursive call on the next node.
  • Return the head.

Below is the implementation of the above approach:

C++




#include <iostream>
using namespace std;
 
// Node of the singly linked list
struct Node {
    int data;
    struct Node* next;
};
 
// Function to insert a node at the beginning of the singly linked list
void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node = new Node;
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}
 
// Recursive function to delete all even nodes from a singly linked list
void deleteEvenNodes(struct Node** head_ref)
{
    if (*head_ref == NULL) {
        return;
    }
    if ((*head_ref)->data % 2 == 0) {
        // If the current node is even, delete it and recursively call the function on the next node
        struct Node* temp = *head_ref;
        *head_ref = (*head_ref)->next;
        delete(temp);
        deleteEvenNodes(head_ref);
    }
    else {
        // If the current node is odd, recursively call the function on the next node
        deleteEvenNodes(&((*head_ref)->next));
    }
}
 
// Function to print the singly linked list
void printList(struct Node* node)
{
    while (node != NULL) {
        cout << node->data << " -> ";
        node = node->next;
    }
    cout << "NULL" << endl;
}
 
// Driver code
int main()
{
    // Start with the empty list
    Node* head = NULL;
 
    // Insert elements into the singly linked list
    push(&head, 2);
    push(&head, 6);
    push(&head, 15);
    push(&head, 16);
    push(&head, 18);
 
    cout << "Initial List: ";
    printList(head);
 
    // Delete all even nodes from the singly linked list
    deleteEvenNodes(&head);
 
    cout << "Final List: ";
    printList(head);
 
    return 0;
}


Java




// Java code for the above approach
 
public class GFG {
 
    // Node of the singly linked list
    static class Node {
        int data;
        Node next;
 
        Node(int data)
        {
            this.data = data;
            this.next = null;
        }
    }
 
    // Function to insert a node at the beginning of the
    // singly linked list
    static Node push(Node head, int new_data)
    {
        Node new_node = new Node(new_data);
        new_node.next = head;
        return new_node;
    }
 
    // Recursive function to delete all even nodes from a
    // singly linked list
    static Node deleteEvenNodes(Node head)
    {
        Node temp = head;
        Node prev = null;
 
        // Iterate through the list
        while (temp != null && temp.data % 2 == 0) {
            head = temp.next;
            temp = head;
        }
 
        // Iterate further to check for even elements and
        // delete them
        while (temp != null) {
            while (temp != null && temp.data % 2 != 0) {
                prev = temp;
                temp = temp.next;
            }
 
            if (temp == null) {
                return head;
            }
 
            prev.next = temp.next;
 
            temp = prev.next;
        }
 
        return head;
    }
 
    // Function to print the singly linked list
    static void printList(Node node)
    {
        while (node != null) {
            System.out.print(node.data + " -> ");
            node = node.next;
        }
        System.out.println("NULL");
    }
 
    public static void main(String[] args)
    {
        // Start with the empty list
        Node head = null;
 
        // Insert elements into the singly linked list
        head = push(head, 2);
        head = push(head, 6);
        head = push(head, 15);
        head = push(head, 16);
        head = push(head, 18);
 
        System.out.print("Initial List: ");
        printList(head);
 
        // Delete all even nodes from the singly linked list
        head = deleteEvenNodes(head);
 
        System.out.print("Final List: ");
        printList(head);
    }
}
 
// This code is contributed by Susobhan Akhuli


Python3




# Node of the singly linked list
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
 
# Function to insert a node at the beginning of the singly linked list
def push(head_ref, new_data):
    new_node = Node(new_data)
    new_node.next = head_ref
    head_ref = new_node
    return head_ref
 
# Recursive function to delete all even nodes from a singly linked list
def deleteEvenNodes(head_ref):
    if head_ref is None:
        return None
    if head_ref.data % 2 == 0:
        # If the current node is even, delete it and recursively call the function on the next node
        temp = head_ref
        head_ref = head_ref.next
        del temp
        head_ref = deleteEvenNodes(head_ref)
    else:
        # If the current node is odd, recursively call the function on the next node
        head_ref.next = deleteEvenNodes(head_ref.next)
    return head_ref
 
# Function to print the singly linked list
def printList(node):
    while node is not None:
        print(node.data, end=" -> ")
        node = node.next
    print("NULL")
 
# Driver code
if __name__ == "__main__":
    # Start with an empty list
    head = None
 
    # Insert elements into the singly linked list
    head = push(head, 2)
    head = push(head, 6)
    head = push(head, 15)
    head = push(head, 16)
    head = push(head, 18)
 
    print("Initial List: ", end="")
    printList(head)
 
    # Delete all even nodes from the singly linked list
    head = deleteEvenNodes(head)
 
    print("Final List: ", end="")
    printList(head)


C#




// C# code for the above approach
using System;
 
// Node of the singly linked list
public class Node {
    public int data;
    public Node next;
 
    // Constructor to initialize a new node
    public Node(int data)
    {
        this.data = data;
        this.next = null;
    }
}
 
public class LinkedList {
    // Function to insert a node at the beginning of the
    // singly linked list
    public static void Push(ref Node headRef, int newData)
    {
        Node newNode = new Node(newData);
        newNode.next = headRef;
        headRef = newNode;
    }
 
    // Recursive function to delete all even nodes from a
    // singly linked list
    public static void DeleteEvenNodes(ref Node headRef)
    {
        if (headRef == null) {
            return;
        }
 
        if (headRef.data % 2 == 0) {
            // If the current node is even, delete it and
            // recursively call the function on the next
            // node
            _ = headRef;
            headRef = headRef.next;
            _ = null;
            DeleteEvenNodes(ref headRef);
        }
        else {
            // If the current node is odd, recursively call
            // the function on the next node
            DeleteEvenNodes(ref headRef.next);
        }
    }
 
    // Function to print the singly linked list
    public static void PrintList(Node node)
    {
        while (node != null) {
            Console.Write(node.data + " -> ");
            node = node.next;
        }
        Console.WriteLine("NULL");
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        // Start with the empty list
        Node head = null;
 
        // Insert elements into the singly linked list
        Push(ref head, 2);
        Push(ref head, 6);
        Push(ref head, 15);
        Push(ref head, 16);
        Push(ref head, 18);
 
        Console.Write("Initial List: ");
        PrintList(head);
 
        // Delete all even nodes from the singly linked list
        DeleteEvenNodes(ref head);
 
        Console.Write("Final List: ");
        PrintList(head);
    }
}
 
// This code is contributed by Susobhan Akhuli


Javascript




// Node of the singly linked list
class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}
 
// Function to insert a node at the beginning of the singly linked list
function push(head, new_data) {
    let new_node = new Node(new_data);
    new_node.next = head;
    return new_node;
}
 
// Recursive function to delete all even nodes from a singly linked list
function deleteEvenNodes(head) {
    if (head === null) {
        return null;
    }
    if (head.data % 2 === 0) {
        // If the current node is even, delete it and recursively call the function on the next node
        let temp = head.next;
        delete head;
        return deleteEvenNodes(temp);
    } else {
        // If the current node is odd, recursively call the function on the next node
        head.next = deleteEvenNodes(head.next);
        return head;
    }
}
 
// Function to print the singly linked list
function printList(node) {
    while (node !== null) {
        console.log(node.data + " -> ");
        node = node.next;
    }
    console.log("NULL");
}
 
// Driver code
function main() {
    // Start with an empty list
    let head = null;
 
    // Insert elements into the singly linked list
    head = push(head, 2);
    head = push(head, 6);
    head = push(head, 15);
    head = push(head, 16);
    head = push(head, 18);
 
    console.log("Initial List: ");
    printList(head);
 
    // Delete all even nodes from the singly linked list
    head = deleteEvenNodes(head);
 
    console.log("Final List: ");
    printList(head);
}
 
main();


Output:

Initial List: 18 -> 16 -> 15 -> 6 -> 2 -> NULL
Final List: 15 -> NULL


Time Complexity: O(n), where n is the number of nodes in the linked list.
Space Complexity: O(n), This is because the function creates n recursive function calls on the call stack, one for each node in the linked list.



Last Updated : 28 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads