📜  单向链表中斐波那契节点的各种操作

📅  最后修改于: 2021-09-03 03:14:06             🧑  作者: Mango

给定一个包含N 个节点的单向链表,任务是对其中存在的斐波那契节点执行以下操作:

  1. 打印单向链表中存在的所有斐波那契节点。
  2. 找出单向链表中存在的斐波那契节点总数。
  3. 找出最小和最大斐波那契节点。
  4. 从单向链表中删除所有斐波那契节点。

例子:

方法:这个想法是使用散列来预先计算并存储 Fibonacci 节点,直到链表中的最大值,使检查变得容易和高效(在 O(1) 时间内)。

  1. 遍历整个单向链表,得到链表中的最大值。
  2. 现在,构建一个哈希表,其中包含所有小于或等于单向链表中最大值的斐波那契节点。

执行上述预计算后,我们可以在恒定时间内检查一个数字是否为斐波那契数列。因此,为了执行上述操作,使用以下方法:

  1. 打印斐波那契节点:遍历链表并检查数字是否为斐波那契值。如果是,则打印它。
  2. 计算斐波那契节点数:为了计算链表中斐波那契节点的数量,我们遍历链表并检查该数字是否为斐波那契值。
  3. 找到最小和最大斐波那契节点:遍历链表并检查节点处的值是否为斐波那契。如是:
    • 如果当前节点的值大于max ,则将当前节点的值分配给 max。
    • 如果当前节点的值小于min ,则将当前节点的值分配给 min。
  4. 删除斐波那契节点:为了删除斐波那契值,遍历链表,如果数据是斐波那契,则使用此方法删除包含数据的节点。

下面是上述方法的实现:

C++
// C++ implementation to perform the
// operations on Fibonacci nodes
// of a Singly Linked list
 
#include 
using namespace std;
 
set hashmap;
 
// Node of the singly linked list
struct Node {
    int data;
    Node* next;
};
 
// Function to insert a node at the beginning
// of the singly Linked List
void push(Node** head_ref, int new_data)
{
    // Allocate a new node
    Node* new_node = new Node;
 
    // Insert the data
    new_node->data = new_data;
    new_node->next = (*head_ref);
 
    // Move the head to point the new node
    (*head_ref) = new_node;
}
 
// Function to delete a node in a SLL
// head_ref --> pointer to head node pointer.
// del --> pointer to node to be deleted
void deleteNode(Node** head_ref, Node* del)
{
    // Base case
    struct Node* temp = *head_ref;
 
    if (*head_ref == NULL || del == NULL)
        return;
 
    // If the node to be deleted is
    // the head node
    if (*head_ref == del)
        *head_ref = del->next;
 
    // Traverse list till not found
    // delete node
    while (temp->next != del) {
        temp = temp->next;
    }
 
    // Copy address of node
    temp->next = del->next;
 
    // Finally, free the memory
    // occupied by del
    free(del);
 
    return;
}
 
// Function that returns the largest element
// from the linked list.
int largestElement(struct Node* head_ref)
{
    // Declare a max variable and
    // initialize it with INT_MIN value.
    // INT_MIN is integer type and
    // its value is -32767 or less.
    int max = INT_MIN;
 
    Node* head = head_ref;
 
    // Loop to iterate the linked list
    while (head != NULL) {
 
        // If max is less than head->data then
        // assign value of head->data to max
        // otherwise node point to next node.
        if (max < head->data)
            max = head->data;
 
        head = head->next;
    }
    return max;
}
 
// Function to create a hash table
// to check Fibonacci nodes
void createHash(int maxElement)
{
    // Insert the first two
    // elements in the hash
    int prev = 0, curr = 1;
    hashmap.insert(prev);
    hashmap.insert(curr);
 
    // Add the elements until the max element
    // by using the previous two numbers
    while (curr <= maxElement) {
        int temp = curr + prev;
        hashmap.insert(temp);
        prev = curr;
        curr = temp;
    }
}
 
// Function to print the Fibonacci
// nodes in a linked list
int printFibonacci(Node** head_ref)
{
 
    int count = 0;
    Node* ptr = *head_ref;
 
    cout << "Fibonacci nodes = ";
 
    while (ptr != NULL) {
 
        // If current node is Fibonacci
        if (hashmap.find(ptr->data)
            != hashmap.end()) {
 
            // Update count
            cout << ptr->data << " ";
        }
 
        ptr = ptr->next;
    }
 
    cout << endl;
    return 0;
}
 
// Function to find the count of Fibonacci
// nodes in a linked list
int countFibonacci(Node** head_ref)
{
 
    int count = 0;
    Node* ptr = *head_ref;
 
    while (ptr != NULL) {
 
        // If current node is Fibonacci
        if (hashmap.find(ptr->data)
            != hashmap.end()) {
 
            // Update count
            count++;
        }
 
        ptr = ptr->next;
    }
 
    return count;
}
 
// Function to find maximum and minimum
// fibonacci nodes in a linked list
void minmaxFibonacciNodes(Node** head_ref)
{
    // Find the largest node value
    // in Singly Linked List
    int maxEle = largestElement(*head_ref);
 
    // Creating a set containing
    // all the Fibonacci nodes
    // upto the maximum data value
    // in the Singly Linked List
    // set hash;
    // createHash(hash, maxEle);
 
    int minimum = INT_MAX;
    int maximum = INT_MIN;
    Node* ptr = *head_ref;
 
    while (ptr != NULL) {
 
        // If current node is fibonacci
        if (hashmap.find(ptr->data)
            != hashmap.end()) {
 
            // Update minimum
            minimum
                = min(minimum, ptr->data);
 
            // Update maximum
            maximum
                = max(maximum, ptr->data);
        }
        ptr = ptr->next;
    }
 
    cout << "Minimum Fibonacci node: "
         << minimum << endl;
    cout << "Maximum Fibonacci node: "
         << maximum << endl;
}
 
// Function to delete all the
// fibonacci nodes from the
// singly linked list
void deleteFibonacciNodes(Node** head_ref)
{
 
    Node* ptr = *head_ref;
    Node* next;
 
    // Iterating through the linked list
    while (ptr != NULL) {
        next = ptr->next;
 
        // If the node's data is fibonacci,
        // delete node 'ptr'
        if (hashmap.find(ptr->data) != hashmap.end())
            deleteNode(head_ref, ptr);
 
        ptr = next;
    }
}
 
// Function to print nodes in a
// given singly linked list
void printList(Node* head)
{
    while (head != NULL) {
        cout << head->data << " ";
        head = head->next;
    }
}
 
void operations(struct Node* head)
{
    // Find the largest node value
    // in Singly Linked List
    int maxEle = largestElement(head);
 
    // Creating a set containing
    // all Fibonacci nodes
    // upto the maximum data value
    // in the Singly Linked List
    createHash(maxEle);
 
    // Print all Fibonacci nodes
    printFibonacci(&head);
 
    // Count of Fibonacci nodes
    cout << "Count of Fibonacci nodes = "
         << countFibonacci(&head) << endl;
 
    // Minimum and maximum Fibonacci nodes
    minmaxFibonacciNodes(&head);
 
    // Delete Fibonacci nodes
    deleteFibonacciNodes(&head);
 
    cout << "List after deletion: ";
    printList(head);
}
 
// Driver program
int main()
{
    // Start with the empty list
    Node* head = NULL;
 
    // Create the linked list
    // 15 -> 16 -> 8 -> 6 -> 13
    push(&head, 13);
    push(&head, 6);
    push(&head, 8);
    push(&head, 16);
    push(&head, 15);
 
    operations(head);
 
    return 0;
}


Java
// Java implementation to perform the
// operations on Fibonacci nodes
// of a Singly Linked list
  
 
import java.util.*;
 
class GFG{
  
static HashSet hashmap = new HashSet();
  
// Node of the singly linked list
static class Node {
    int data;
    Node next;
};
  
// Function to insert a node at the beginning
// of the singly Linked List
static Node push(Node head_ref, int new_data)
{
    // Allocate a new node
    Node new_node = new Node();
  
    // Insert the data
    new_node.data = new_data;
    new_node.next = head_ref;
  
    // Move the head to point the new node
    head_ref = new_node;
    return head_ref;
}
  
// Function to delete a node in a SLL
// head_ref -. pointer to head node pointer.
// del -. pointer to node to be deleted
static Node deleteNode(Node head_ref, Node del)
{
    // Base case
    Node temp = head_ref;
  
    if (head_ref == null || del == null)
        return null;
  
    // If the node to be deleted is
    // the head node
    if (head_ref == del)
        head_ref = del.next;
  
    // Traverse list till not found
    // delete node
    while (temp.next != del) {
        temp = temp.next;
    }
  
    // Copy address of node
    temp.next = del.next;
  
    // Finally, free the memory
    // occupied by del
    del = null;
  
    return head_ref;
}
  
// Function that returns the largest element
// from the linked list.
static int largestElement(Node head_ref)
{
    // Declare a max variable and
    // initialize it with Integer.MIN_VALUE value.
    // Integer.MIN_VALUE is integer type and
    // its value is -32767 or less.
    int max = Integer.MIN_VALUE;
  
    Node head = head_ref;
  
    // Loop to iterate the linked list
    while (head != null) {
  
        // If max is less than head.data then
        // assign value of head.data to max
        // otherwise node point to next node.
        if (max < head.data)
            max = head.data;
  
        head = head.next;
    }
    return max;
}
  
// Function to create a hash table
// to check Fibonacci nodes
static void createHash(int maxElement)
{
    // Insert the first two
    // elements in the hash
    int prev = 0, curr = 1;
    hashmap.add(prev);
    hashmap.add(curr);
  
    // Add the elements until the max element
    // by using the previous two numbers
    while (curr <= maxElement) {
        int temp = curr + prev;
        hashmap.add(temp);
        prev = curr;
        curr = temp;
    }
}
  
// Function to print the Fibonacci
// nodes in a linked list
static int printFibonacci(Node head_ref)
{
  
    int count = 0;
    Node ptr = head_ref;
  
    System.out.print("Fibonacci nodes = ");
  
    while (ptr != null) {
  
        // If current node is Fibonacci
        if (hashmap.contains(ptr.data)) {
  
            // Update count
            System.out.print(ptr.data+ " ");
        }
  
        ptr = ptr.next;
    }
  
    System.out.println();
    return 0;
}
  
// Function to find the count of Fibonacci
// nodes in a linked list
static int countFibonacci(Node head_ref)
{
  
    int count = 0;
    Node ptr = head_ref;
  
    while (ptr != null) {
  
        // If current node is Fibonacci
        if (hashmap.contains(ptr.data)) {
  
            // Update count
            count++;
        }
  
        ptr = ptr.next;
    }
  
    return count;
}
  
// Function to find maximum and minimum
// fibonacci nodes in a linked list
static void minmaxFibonacciNodes(Node head_ref)
{
    // Find the largest node value
    // in Singly Linked List
    int maxEle = largestElement(head_ref);
  
    // Creating a set containing
    // all the Fibonacci nodes
    // upto the maximum data value
    // in the Singly Linked List
    // HashSet hash;
    // createHash(hash, maxEle);
  
    int minimum = Integer.MAX_VALUE;
    int maximum = Integer.MIN_VALUE;
    Node ptr = head_ref;
  
    while (ptr != null) {
  
        // If current node is fibonacci
        if (hashmap.contains(ptr.data)) {
  
            // Update minimum
            minimum
                = Math.min(minimum, ptr.data);
  
            // Update maximum
            maximum
                = Math.max(maximum, ptr.data);
        }
        ptr = ptr.next;
    }
  
    System.out.print("Minimum Fibonacci node: "
         + minimum +"\n");
    System.out.print("Maximum Fibonacci node: "
         + maximum +"\n");
}
  
// Function to delete all the
// fibonacci nodes from the
// singly linked list
static Node deleteFibonacciNodes(Node head_ref)
{
  
    Node ptr = head_ref;
    Node next;
  
    // Iterating through the linked list
    while (ptr != null) {
        next = ptr.next;
  
        // If the node's data is fibonacci,
        // delete node 'ptr'
        if (hashmap.contains(ptr.data))
            deleteNode(head_ref, ptr);
  
        ptr = next;
    }
    return head_ref;
}
  
// Function to print nodes in a
// given singly linked list
static void printList(Node head)
{
    while (head != null) {
        System.out.print(head.data+ " ");
        head = head.next;
    }
}
  
static void operations(Node head)
{
    // Find the largest node value
    // in Singly Linked List
    int maxEle = largestElement(head);
  
    // Creating a set containing
    // all Fibonacci nodes
    // upto the maximum data value
    // in the Singly Linked List
    createHash(maxEle);
  
    // Print all Fibonacci nodes
    printFibonacci(head);
  
    // Count of Fibonacci nodes
    System.out.print("Count of Fibonacci nodes = "
         + countFibonacci(head) +"\n");
  
    // Minimum and maximum Fibonacci nodes
    minmaxFibonacciNodes(head);
  
    // Delete Fibonacci nodes
    head = deleteFibonacciNodes(head);
  
    System.out.print("List after deletion: ");
    printList(head);
}
  
// Driver program
public static void main(String[] args)
{
    // Start with the empty list
    Node head = null;
  
    // Create the 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);
  
    operations(head);
  
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 implementation to perform the
# operations on Fibonacci nodes
# of a Singly Linked list
 
hashmap = set()
 
# Node of the singly linked list
class Node:
     
    def __init(self):
        self.data = 0
        self.next = None
         
# Function to add a node at the beginning
# of the singly Linked List
def push(head_ref, new_data):
 
    # Allocate a new node
    new_node = Node()
 
    # Insert the data
    new_node.data = new_data;
    new_node.next = (head_ref);
 
    # Move the head to point the new node
    (head_ref) = new_node;
     
    return head_ref
  
# Function to delete a node in a SLL
# head_ref -. pointer to head node pointer.
# delt -. pointer to node to be deleted
def deleteNode(head_ref, delt):
 
    # Base case
    temp = head_ref;
 
    if (head_ref == None or delt == None):
        return;
 
    # If the node to be deleted is
    # the head node
    if (head_ref == delt):
        head_ref = delt.next;
 
    # Traverse list till not found
    # delete node
    while (temp.next != delt):
        temp = temp.next;
     
 
    # Copy address of node
    temp.next = delt.next;
 
    # Finally, free the memory
    # occupied by delt
    del(delt);
 
    return;
 
# Function that returns the largest element
# from the linked list.
def largestElement(head_ref):
 
    # Declare a max variable and
    # initialize it with INT_MIN value.
    # INT_MIN is integer type and
    # its value is -32767 or less.
    max = -10000000
 
    head = head_ref;
 
    # Loop to iterate the linked list
    while (head != None):
 
        # If max is less than head.data then
        # assign value of head.data to max
        # otherwise node point to next node.
        if (max < head.data):
            max = head.data;
 
        head = head.next;
     
    return max;
 
# Function to create a hash table
# to check Fibonacci nodes
def createHash(maxElement):
 
    # Insert the first two
    # elements in the hash
    prev = 0
    curr = 1;
    hashmap.add(prev);
    hashmap.add(curr);
 
    # Add the elements until the max element
    # by using the previous two numbers
    while (curr <= maxElement):
        temp = curr + prev;
        hashmap.add(temp);
        prev = curr;
        curr = temp;
     
# Function to print the Fibonacci
# nodes in a linked list
def printFibonacci(head_ref):
 
    count = 0;
    ptr = head_ref
     
    print("Fibonacci nodes = ",end='')
 
    while (ptr != None):
 
        # If current node is Fibonacci
        if (ptr.data in hashmap):
 
            # Update count
            print(ptr.data, end=' ')
 
        ptr = ptr.next;
         
    print()
 
    return 0;
  
# Function to find the count of Fibonacci
# nodes in a linked list
def countFibonacci(head_ref):
 
    count = 0;
    ptr = head_ref;
 
    while (ptr != None):
 
        # If current node is Fibonacci
        if (ptr.data in hashmap):
 
            # Update count
            count += 1
 
        ptr = ptr.next;
 
    return count;
 
# Function to find maximum and minimum
# fibonacci nodes in a linked list
def minmaxFibonacciNodes(head_ref):
 
    # Find the largest node value
    # in Singly Linked List
    maxEle = largestElement(head_ref);
 
    # Creating a set containing
    # all the Fibonacci nodes
    # upto the maximum data value
    # in the Singly Linked List
    # set hash;
    # createHash(hash, maxEle);
    minimum = 100000000
    maximum = -100000000
    ptr = head_ref;
 
    while (ptr != None):
 
        # If current node is fibonacci
        if (ptr.data in hashmap):
 
            # Update minimum
            minimum = min(minimum, ptr.data);
 
            # Update maximum
            maximum = max(maximum, ptr.data);
         
        ptr = ptr.next;
     
    print("Minimum Fibonacci node: "+str(minimum))
    print("Maximum Fibonacci node: "+str(maximum))
 
# Function to delete all the
# fibonacci nodes from the
# singly linked list
def deleteFibonacciNodes(head_ref):
 
    ptr = head_ref;
    next = None
 
    # Iterating through the linked list
    while (ptr != None):
        next = ptr.next;
 
        # If the node's data is fibonacci,
        # delete node 'ptr'
        if (ptr.data in hashmap):
             
            deleteNode(head_ref, ptr);
 
        ptr = next;
 
# Function to print nodes in a
# given singly linked list
def printList(head):
 
    while (head != None):
        print(head.data, end = ' ')
        head = head.next;
     
def operations(head):
 
    # Find the largest node value
    # in Singly Linked List
    maxEle = largestElement(head);
 
    # Creating a set containing
    # all Fibonacci nodes
    # upto the maximum data value
    # in the Singly Linked List
    createHash(maxEle);
 
    # Print all Fibonacci nodes
    printFibonacci(head);
 
    # Count of Fibonacci nodes
    print("Count of Fibonacci nodes = " + str(countFibonacci(head)))
 
    # Minimum and maximum Fibonacci nodes
    minmaxFibonacciNodes(head);
 
    # Delete Fibonacci nodes
    deleteFibonacciNodes(head);
    print("List after deletion: ", end='')
 
    printList(head);
  
# Driver program
if __name__=='__main__':
     
    # Start with the empty list
    head = None;
 
    # Create the 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);
 
    operations(head);
 
# This code is contributed by rutvik_56


C#
// C# implementation to perform the
// operations on Fibonacci nodes
// of a Singly Linked list
using System;
using System.Collections.Generic;
 
class GFG{
   
static HashSet hashmap = new HashSet();
   
// Node of the singly linked list
class Node {
    public int data;
    public Node next;
};
   
// Function to insert a node at the beginning
// of the singly Linked List
static Node push(Node head_ref, int new_data)
{
    // Allocate a new node
    Node new_node = new Node();
   
    // Insert the data
    new_node.data = new_data;
    new_node.next = head_ref;
   
    // Move the head to point the new node
    head_ref = new_node;
    return head_ref;
}
   
// Function to delete a node in a SLL
// head_ref -. pointer to head node pointer.
// del -. pointer to node to be deleted
static Node deleteNode(Node head_ref, Node del)
{
    // Base case
    Node temp = head_ref;
   
    if (head_ref == null || del == null)
        return null;
   
    // If the node to be deleted is
    // the head node
    if (head_ref == del)
        head_ref = del.next;
   
    // Traverse list till not found
    // delete node
    while (temp.next != del) {
        temp = temp.next;
    }
   
    // Copy address of node
    temp.next = del.next;
   
    // Finally, free the memory
    // occupied by del
    del = null;
   
    return head_ref;
}
   
// Function that returns the largest element
// from the linked list.
static int largestElement(Node head_ref)
{
    // Declare a max variable and
    // initialize it with int.MinValue value.
    // int.MinValue is integer type and
    // its value is -32767 or less.
    int max = int.MinValue;
   
    Node head = head_ref;
   
    // Loop to iterate the linked list
    while (head != null) {
   
        // If max is less than head.data then
        // assign value of head.data to max
        // otherwise node point to next node.
        if (max < head.data)
            max = head.data;
   
        head = head.next;
    }
    return max;
}
   
// Function to create a hash table
// to check Fibonacci nodes
static void createHash(int maxElement)
{
    // Insert the first two
    // elements in the hash
    int prev = 0, curr = 1;
    hashmap.Add(prev);
    hashmap.Add(curr);
   
    // Add the elements until the max element
    // by using the previous two numbers
    while (curr <= maxElement) {
        int temp = curr + prev;
        hashmap.Add(temp);
        prev = curr;
        curr = temp;
    }
}
   
// Function to print the Fibonacci
// nodes in a linked list
static int printFibonacci(Node head_ref)
{
   
    Node ptr = head_ref;
   
    Console.Write("Fibonacci nodes = ");
   
    while (ptr != null) {
   
        // If current node is Fibonacci
        if (hashmap.Contains(ptr.data)) {
   
            // Update count
            Console.Write(ptr.data+ " ");
        }
   
        ptr = ptr.next;
    }
   
    Console.WriteLine();
    return 0;
}
   
// Function to find the count of Fibonacci
// nodes in a linked list
static int countFibonacci(Node head_ref)
{
   
    int count = 0;
    Node ptr = head_ref;
   
    while (ptr != null) {
   
        // If current node is Fibonacci
        if (hashmap.Contains(ptr.data)) {
   
            // Update count
            count++;
        }
   
        ptr = ptr.next;
    }
   
    return count;
}
   
// Function to find maximum and minimum
// fibonacci nodes in a linked list
static void minmaxFibonacciNodes(Node head_ref)
{
    // Find the largest node value
    // in Singly Linked List
    int maxEle = largestElement(head_ref);
   
    // Creating a set containing
    // all the Fibonacci nodes
    // upto the maximum data value
    // in the Singly Linked List
    // HashSet hash;
    // createHash(hash, maxEle);
   
    int minimum = int.MaxValue;
    int maximum = int.MinValue;
    Node ptr = head_ref;
   
    while (ptr != null) {
   
        // If current node is fibonacci
        if (hashmap.Contains(ptr.data)) {
   
            // Update minimum
            minimum
                = Math.Min(minimum, ptr.data);
   
            // Update maximum
            maximum
                = Math.Max(maximum, ptr.data);
        }
        ptr = ptr.next;
    }
   
    Console.Write("Minimum Fibonacci node: "
         + minimum +"\n");
    Console.Write("Maximum Fibonacci node: "
         + maximum +"\n");
}
   
// Function to delete all the
// fibonacci nodes from the
// singly linked list
static Node deleteFibonacciNodes(Node head_ref)
{
   
    Node ptr = head_ref;
    Node next;
   
    // Iterating through the linked list
    while (ptr != null) {
        next = ptr.next;
   
        // If the node's data is fibonacci,
        // delete node 'ptr'
        if (hashmap.Contains(ptr.data))
            deleteNode(head_ref, ptr);
   
        ptr = next;
    }
    return head_ref;
}
   
// Function to print nodes in a
// given singly linked list
static void printList(Node head)
{
    while (head != null) {
        Console.Write(head.data+ " ");
        head = head.next;
    }
}
   
static void operations(Node head)
{
    // Find the largest node value
    // in Singly Linked List
    int maxEle = largestElement(head);
   
    // Creating a set containing
    // all Fibonacci nodes
    // upto the maximum data value
    // in the Singly Linked List
    createHash(maxEle);
   
    // Print all Fibonacci nodes
    printFibonacci(head);
   
    // Count of Fibonacci nodes
    Console.Write("Count of Fibonacci nodes = "
         + countFibonacci(head) +"\n");
   
    // Minimum and maximum Fibonacci nodes
    minmaxFibonacciNodes(head);
   
    // Delete Fibonacci nodes
    head = deleteFibonacciNodes(head);
   
    Console.Write("List after deletion: ");
    printList(head);
}
   
// Driver program
public static void Main(String[] args)
{
    // Start with the empty list
    Node head = null;
   
    // Create the 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);
   
    operations(head);
   
}
}
 
// This code is contributed by Princi Singh


Javascript


输出:
Fibonacci nodes = 8 13 
Count of Fibonacci nodes = 2
Minimum Fibonacci node: 8
Maximum Fibonacci node: 13
List after deletion: 15 16 6

时间复杂度: O(N) ,其中 N 是链表中的节点数。

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live