Open In App

Remove all nodes from a Doubly Linked List containing Fibonacci numbers

Improve
Improve
Like Article
Like
Save
Share
Report

Given a doubly linked list containing N nodes, the task is to remove all the nodes from the list which contains Fibonacci numbers.
Examples: 

Input: DLL = 15 <=> 16 <=> 8 <=> 7 <=> 13 
Output: 15 <=> 16 <=> 7 
Explanation: 
The linked list contains two fibonacci numbers 8 and 13. 
Hence, these nodes have been deleted.
Input: DLL = 5 <=> 3 <=> 4 <=> 2 <=> 9 
Output: 4 <=> 9 
Explanation: 
The linked list contains three fibonacci numbers 5, 3 and 2. 
Hence, these nodes have been deleted. 
 

Approach: The idea is to use hashing to store and check the Fibonacci numbers
 

  1. Traverse through the entire doubly linked list and obtain the maximum value in the list.
  2. Now, in order to check for the Fibonacci numbers, build a hash table containing all the Fibonacci numbers less than or equal to the maximum value in the linked list.
  3. Finally, traverse the nodes of the doubly linked list one by one and remove the nodes which contain Fibonacci numbers as their data value.

Below is the implementation of the above approach: 
 

C++




// C++ implementation to delete all
// Fibonacci nodes from the
// doubly linked list
 
#include
 
using namespace std;
 
// Node of the doubly linked list
struct Node {
    int data;
    Node *prev, *next;
};
 
// Function to insert a node at the beginning
// of the Doubly Linked List
void push(Node** head_ref, int new_data)
{
    // Allocate the node
    Node* new_node
        = (Node*)malloc(sizeof(struct Node));
 
    // Insert the data
    new_node->data = new_data;
 
    // Since we are adding at the beginning,
    // prev is always NULL
    new_node->prev = NULL;
 
    // Link the old list of the new node
    new_node->next = (*head_ref);
 
    // Change the prev of head node to new node
    if ((*head_ref) != NULL)
        (*head_ref)->prev = new_node;
 
    // Move the head to point to the new node
    (*head_ref) = new_node;
}
 
// Function to find the largest
// nodes in the Doubly Linked List
int LargestInDLL(struct Node** head_ref)
{
    struct Node *max, *temp;
 
    // Initialize two-pointer temp
    // and max on the head node
    temp = max = *head_ref;
 
    // Traverse the whole doubly linked list
    while (temp != NULL) {
 
        // If temp's data is greater than
        // the max's data, then max = temp
        // and return max->data
        if (temp->data > max->data)
            max = temp;
 
        temp = temp->next;
    }
    return max->data;
}
 
// Function to create hash table to
// check Fibonacci numbers
void createHash(set& hash, int maxElement)
{
    int prev = 0, curr = 1;
    hash.insert(prev);
    hash.insert(curr);
 
    // Inserting the Fibonacci numbers
    // until the maximum element in the
    // Linked List
    while (curr  pointer to head node pointer.
// del --> pointer to node to be deleted
void deleteNode(Node** head_ref, Node* del)
{
    // Base case
    if (*head_ref == NULL || del == NULL)
        return;
 
    // If the node to be deleted is head node
    if (*head_ref == del)
        *head_ref = del->next;
 
    // Change next only if node to be
    // deleted is not the last node
    if (del->next != NULL)
        del->next->prev = del->prev;
 
    // Change prev only if node to be
    // deleted is not the first node
    if (del->prev != NULL)
        del->prev->next = del->next;
 
    // Finally, free the memory
    // occupied by del
    free(del);
 
    return;
}
 
// Function to delete all fibonacci nodes
// from the doubly linked list
void deleteFibonacciNodes(Node** head_ref)
{
    // Find the largest node value
    // in Doubly Linked List
    int maxEle = LargestInDLL(head_ref);
 
    // Creating a set containing
    // all the fibonacci numbers
    // upto the maximum data value
    // in the Doubly Linked List
    set hash;
    createHash(hash, maxEle);
 
    Node* ptr = *head_ref;
    Node* next;
 
    // Iterating through the linked list
    while (ptr != NULL) {
        next = ptr->next;
 
        // If node's data is fibonacci,
        // delete node 'ptr'
        if (hash.find(ptr->data) != hash.end())
            deleteNode(head_ref, ptr);
 
        ptr = next;
    }
}
 
// Function to print nodes in a
// given doubly linked list
void printList(Node* head)
{
    while (head != NULL) {
        cout <data <next;
    }
}
 
// Driver program
int main()
{
 
    Node* head = NULL;
 
    // Create the doubly linked list
    // 15  16  8  6  13
    push(&head, 13);
    push(&head, 6);
    push(&head, 8);
    push(&head, 16);
    push(&head, 15);
 
    cout << "Original List: ";
    printList(head);
 
    deleteFibonacciNodes(&head);
 
    cout << "\nModified List: ";
    printList(head);
}


Java




// Java implementation to delete all Fibonacci nodes from
// the doubly linked list
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Node of a doubly linked list
    class Node {
        int data;
        Node next, prev;
    }
 
    Node head = null;
 
    HashSet<Integer> hashset = new HashSet<Integer>();
 
    // Function to add a node at the beginning of the doubly
    // linked list.
    public Node push(int new_data)
    {
 
        // Allocate the node
        Node new_node = new Node();
 
        // Insert the data
        new_node.data = new_data;
 
        // Since we are adding at the beginning, prev is
        // always null
        new_node.prev = null;
 
        // Link the old list of the new node
        new_node.next = head;
 
        // change the prev of head node to new node
        if (head != null) {
            head.prev = new_node;
        }
 
        // move the head to point to the new node.
        head = new_node;
        return head;
    }
 
    // Function to find the largest nodes in the doubly
    // linked list.
    public int LargestInDLL()
    {
 
        // Initialize two pointer temp and max on to the
        // head node.
        Node max = head;
        Node temp = head;
 
        // Traverse the whole doubly linked list
        while (temp != null) {
 
            // If temp's data is greater than the max's
            // data, then max = temp and return max.data
            if (temp.data > max.data) {
                max = temp;
            }
            temp = temp.next;
        }
        return max.data;
    }
 
    // Function to create hashset table to check Fibonacci
    // numbers
    public void createHash(int maxElement)
    {
        int prev = 0, curr = 1;
        hashset.add(prev);
        hashset.add(curr);
 
        // Inserting the Fibonacci numbers until the maximum
        // element in the Linked List.
        while (curr <= maxElement) {
            int temp = curr + prev;
            hashset.add(temp);
            prev = curr;
            curr = temp;
        }
    }
 
    // Function to delete a node in a Doubly linked list.
    // delt -> pointer to node to be deleted.
    public void deleteNode(Node delt)
    {
 
        // Base case
        if (head == null || delt == null) {
            return;
        }
 
        // If the node to be deleted is head node
        if (head == delt) {
            head = delt.next;
        }
 
        // Change next only if node to be delete is not the
        // last node
        if (delt.next != null) {
            delt.next.prev = delt.prev;
        }
 
        // Change prev only if node to be deleted is not the
        // first node
        if (delt.prev != null) {
            delt.prev.next = delt.next;
        }
        return;
    }
 
    // Function to delete all fibonacci nodes from the
    // doubly linked list.
    public void deleteFibonacciNodes()
    {
 
        // Find the largest node value in doubly linked
        // list.
        int maxEle = LargestInDLL();
 
        createHash(maxEle);
 
        Node ptr = head;
        Node next = null;
 
        // Iterating through the linked list
        while (ptr != null) {
            next = ptr.next;
            // If node's data is fibonacci, delete node
            // 'ptr'
            if (hashset.contains(ptr.data)) {
                deleteNode(ptr);
            }
            ptr = next;
        }
    }
 
    // Function to print nodes in a given doubly linked
    // list.
    public void printList()
    {
        Node curr = head;
        while (curr != null) {
            System.out.print(curr.data + " ");
            curr = curr.next;
        }
        System.out.println();
    }
 
    public static void main(String[] args)
    {
 
        GFG l = new GFG();
 
        // Create the doubly linked list.
 
        // null<- 15 <-> 16 <-> 8 <-> 6 <-> 13 -> null
 
        l.push(13);
        l.push(6);
        l.push(8);
        l.push(16);
        l.push(15);
 
        System.out.print("Original List: ");
        l.printList();
 
        l.deleteFibonacciNodes();
 
        System.out.print("Modilied List: ");
        l.printList();
    }
}
 
// This code is contributed by lokeshmvs21


Python3




# Python3 implementation to delete all
# Fibonacci nodes from the
# doubly linked list
 
# Node of the doubly linked list
class Node:
     
    def __init__(self):
         
        self.data = 0
        self.next = None
        self.prev = None
     
# Function to add a node at the beginning
# of the Doubly Linked List
def push(head_ref, new_data):
 
    # Allocate the node
    new_node = Node()
 
    # Insert the data
    new_node.data = new_data;
 
    # Since we are adding at the beginning,
    # prev is always None
    new_node.prev = None;
 
    # Link the old list of the new node
    new_node.next = (head_ref);
 
    # Change the prev of head node to new node
    if ((head_ref) != None):
        (head_ref).prev = new_node;
 
    # Move the head to point to the new node
    (head_ref) = new_node;
     
    return head_ref
 
# Function to find the largest
# nodes in the Doubly Linked List
def LargestInDLL(head_ref):
 
    max = None
    temp = None
 
    # Initialize two-pointer temp
    # and max on the head node
    temp = max = head_ref;
 
    # Traverse the whole doubly linked list
    while (temp != None):
 
        # If temp's data is greater than
        # the max's data, then max = temp
        # and return max.data
        if (temp.data > max.data):
            max = temp;
 
        temp = temp.next;
     
    return max.data;
 
 
# Function to create hashset table to
# check Fibonacci numbers
def createHash( hashset, maxElement):
 
    prev = 0
    curr = 1;
    hashset.add(prev);
    hashset.add(curr);
 
    # Inserting the Fibonacci numbers
    # until the maximum element in the
    # Linked List
    while (curr <= maxElement):
        temp = curr + prev;
        hashset.add(temp);
        prev = curr;
        curr = temp;
     
# Function to delete a node
# in a Doubly Linked List.
# head_ref -. pointer to head node pointer.
# delt -. pointer to node to be deleted
def deleteNode(head_ref, delt):
 
    # Base case
    if (head_ref == None or delt == None):
        return;
 
    # If the node to be deleted is head node
    if (head_ref == delt):
        head_ref = delt.next;
 
    # Change next only if node to be
    # deleted is not the last node
    if (delt.next != None):
        delt.next.prev = delt.prev;
 
    # Change prev only if node to be
    # deleted is not the first node
    if (delt.prev != None):
        delt.prev.next = delt.next;
 
    # Finally, free the memory
    # occupied by delt
    del(delt);
 
    return;
 
# Function to delete all fibonacci nodes
# from the doubly linked list
def deleteFibonacciNodes(head_ref):
 
    # Find the largest node value
    # in Doubly Linked List
    maxEle = LargestInDLL(head_ref);
 
    # Creating a set containing
    # all the fibonacci numbers
    # upto the maximum data value
    # in the Doubly Linked List
    hashset = set()
    createHash(hashset, maxEle);
 
    ptr = head_ref;
    next=None
 
    # Iterating through the linked list
    while (ptr != None):
        next = ptr.next;
 
        # If node's data is fibonacci,
        # delete node 'ptr'
        if (ptr.data in hashset):
            deleteNode(head_ref, ptr);
 
        ptr = next;
     
# Function to print nodes in a
# given doubly linked list
def printList(head):
 
    while (head != None):
         
        print(head.data, end = ' ')
        head = head.next;
     
# Driver program
if __name__=='__main__':
 
    head = None;
 
    # Create the doubly linked list
    # 15 <. 16 <. 8 <. 6 <. 13
    head = push(head, 13);
    head = push(head, 6);
    head = push(head, 8);
    head = push(head, 16);
    head = push(head, 15);
     
    print("Original List: ", end='')
    printList(head);
 
    deleteFibonacciNodes(head);
     
    print("\nModified List: ", end='')
    printList(head);
 
# This code is contributed by rutvik_56


C#




// C# implementation to delete all Fibonacci nodes from
// the doubly linked list
using System;
using System.Collections.Generic;
 
public class GFG {
 
  // Node of a doubly linked list
  class Node {
    public int data;
    public Node next, prev;
  }
 
  Node head = null;
 
  HashSet<int> hashset = new HashSet<int>();
 
  // Function to add a node at the beginning of the doubly
  // linked list.
  Node push(int new_data)
  {
 
    // Allocate the node
    Node new_node = new Node();
 
    // Insert the data
    new_node.data = new_data;
 
    // Since we are adding at the beginning, prev is
    // always null
    new_node.prev = null;
 
    // Link the old list of the new node
    new_node.next = head;
 
    // change the prev of head node to new node
    if (head != null) {
      head.prev = new_node;
    }
 
    // move the head to point to the new node.
    head = new_node;
    return head;
  }
 
  // Function to find the largest nodes in the doubly
  // linked list.
  int LargestInDLL()
  {
 
    // Initialize two pointer temp and max on to the
    // head node.
    Node max = head;
    Node temp = head;
 
    // Traverse the whole doubly linked list
    while (temp != null) {
 
      // If temp's data is greater than the max's
      // data, then max = temp and return max.data
      if (temp.data > max.data) {
        max = temp;
      }
      temp = temp.next;
    }
    return max.data;
  }
 
  // Function to create hashset table to check Fibonacci
  // numbers
  void createHash(int maxElement)
  {
    int prev = 0, curr = 1;
    hashset.Add(prev);
    hashset.Add(curr);
 
    // Inserting the Fibonacci numbers until the maximum
    // element in the Linked List.
    while (curr <= maxElement) {
      int temp = curr + prev;
      hashset.Add(temp);
      prev = curr;
      curr = temp;
    }
  }
 
  // Function to delete a node in a Doubly linked list.
  // delt -> pointer to node to be deleted.
  void deleteNode(Node delt)
  {
 
    // Base case
    if (head == null || delt == null) {
      return;
    }
 
    // If the node to be deleted is head node
    if (head == delt) {
      head = delt.next;
    }
 
    // Change next only if node to be delete is not the
    // last node
    if (delt.next != null) {
      delt.next.prev = delt.prev;
    }
 
    // Change prev only if node to be deleted is not the
    // first node
    if (delt.prev != null) {
      delt.prev.next = delt.next;
    }
    return;
  }
 
  // Function to delete all fibonacci nodes from the
  // doubly linked list.
  void deleteFibonacciNodes()
  {
 
    // Find the largest node value in doubly linked
    // list.
    int maxEle = LargestInDLL();
 
    createHash(maxEle);
 
    Node ptr = head;
    Node next = null;
 
    // Iterating through the linked list
    while (ptr != null) {
      next = ptr.next;
      // If node's data is fibonacci, delete node
      // 'ptr'
      if (hashset.Contains(ptr.data)) {
        deleteNode(ptr);
      }
      ptr = next;
    }
  }
 
  // Function to print nodes in a given doubly linked
  // list.
  void printList()
  {
    Node curr = head;
    while (curr != null) {
      Console.Write(curr.data + " ");
      curr = curr.next;
    }
    Console.WriteLine();
  }
 
  static public void Main()
  {
 
    GFG l = new GFG();
 
    // Create the doubly linked list.
 
    // null<- 15 <-> 16 <-> 8 <-> 6 <-> 13 -> null
 
    l.push(13);
    l.push(6);
    l.push(8);
    l.push(16);
    l.push(15);
 
    Console.Write("Original List: ");
    l.printList();
 
    l.deleteFibonacciNodes();
 
    Console.Write("Modilied List: ");
    l.printList();
  }
}
 
// This code is contributed by lokeshmvs21


Javascript




// Java implementation to delete all Fibonacci nodes from
// the doubly linked list
 
// Node of a doubly linked list
class Node {
     
    constructor(){
        this.data = 0;
        this.next = null;
        this.prev = null;
    }
}
 
let head = null;
 
let hashset = new Set();
 
// Function to add a node at the beginning of the doubly
// linked list.
function push(new_data)
{
 
    // Allocate the node
    let new_node = new Node();
 
    // Insert the data
    new_node.data = new_data;
 
    // Since we are adding at the beginning, prev is
    // always null
    new_node.prev = null;
 
    // Link the old list of the new node
    new_node.next = head;
 
    // change the prev of head node to new node
    if (head != null) {
        head.prev = new_node;
    }
 
    // move the head to point to the new node.
    head = new_node;
    return head;
}
 
// Function to find the largest nodes in the doubly
// linked list.
function LargestInDLL()
{
 
    // Initialize two pointer temp and max on to the
    // head node.
    let max = head;
    let temp = head;
 
    // Traverse the whole doubly linked list
    while (temp != null) {
 
        // If temp's data is greater than the max's
        // data, then max = temp and return max.data
        if (temp.data > max.data) {
            max = temp;
        }
        temp = temp.next;
    }
    return max.data;
}
 
// Function to create hashset table to check Fibonacci
// numbers
function createHash(maxElement)
{
    let prev = 0, curr = 1;
    hashset.add(prev);
    hashset.add(curr);
 
    // Inserting the Fibonacci numbers until the maximum
    // element in the Linked List.
    while (curr <= maxElement) {
        let temp = curr + prev;
        hashset.add(temp);
        prev = curr;
        curr = temp;
    }
}
 
// Function to delete a node in a Doubly linked list.
// delt -> pointer to node to be deleted.
function deleteNode(delt)
{
 
    // Base case
    if (head == null || delt == null) {
        return;
    }
 
    // If the node to be deleted is head node
    if (head == delt) {
        head = delt.next;
    }
 
    // Change next only if node to be delete is not the
    // last node
    if (delt.next != null) {
        delt.next.prev = delt.prev;
    }
 
    // Change prev only if node to be deleted is not the
    // first node
    if (delt.prev != null) {
        delt.prev.next = delt.next;
    }
    return;
}
 
// Function to delete all fibonacci nodes from the
// doubly linked list.
function deleteFibonacciNodes()
{
 
    // Find the largest node value in doubly linked
    // list.
    let maxEle = LargestInDLL();
 
    createHash(maxEle);
 
    let ptr = head;
    let next = null;
 
    // Iterating through the linked list
    while (ptr != null) {
        next = ptr.next;
        // If node's data is fibonacci, delete node
        // 'ptr'
        if (hashset.has(ptr.data)) {
            deleteNode(ptr);
        }
        ptr = next;
    }
}
 
// Function to print nodes in a given doubly linked
// list.
function printList()
{
    let curr = head;
    while (curr != null) {
        document.write(curr.data + " ");
        curr = curr.next;
    }
    document.write("\n");
}
 
 
// Create the doubly linked list.
 
// null<- 15 <-> 16 <-> 8 <-> 6 <-> 13 -> null
 
push(13);
push(6);
push(8);
push(16);
push(15);
 
console.log("Original List: ");
printList();
 
deleteFibonacciNodes();
 
console.log("Modilied List: ");
printList();
 
// This code is contributed by Nidhi goel.


Output: 

Original List: 15 16 8 6 13 
Modified List: 15 16 6

 

Time Complexity: O(N), where N is the total number of nodes.



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