Move the First Fibonacci Number to the End of a Linked List
Last Updated :
23 Dec, 2023
Given a singly linked list, the task is to identify the first Fibonacci number in the list and move that node to the end of the linked list.
Examples:
Input: 10 -> 15 -> 8 -> 13 -> 21 -> 5 -> 2 -> NULL
Output: 10 -> 15 -> 13 -> 21 -> 5 -> 2 -> 8 -> NULL
Explanation: In the given list, the Fibonacci numbers are 8, 13, 21 and 2. The first Fibonacci number is 8, and we move the node containing 8 to the end.
Input: 3 -> 1 -> 4 -> 11 -> 6 -> 18 -> 24 -> NULL
Output: 1 -> 4 -> 11 -> 6 -> 18 -> 24 -> 3 -> NULL
Explanation: In the given list, the Fibonacci numbers are 3 and 1. The first Fibonacci number is 3, and we move the node containing 3 to the end.
Approach: To solve the problem follow the below idea:
The approach starts by traversing the linked list to identify the first Fibonacci number. It does this by iteratively checking if each number in the list is a Fibonacci number using the "isFibonacci" function. When the first Fibonacci number is found, it records both the node containing it and the previous node. Then, it adjusts the pointers to remove the first Fibonacci node from its current position and appends it to the end of the list. This approach efficiently handles various cases, ensuring that the first Fibonacci number is correctly moved to the list's end while maintaining the order of other nodes.
Steps of the approach:
- Create a function, isFibonacci, to check if a given number is a Fibonacci number. This function iterates through Fibonacci numbers until it reaches or surpasses the given number.
- Implement the moveFirstFibonacciToEnd function to move the first Fibonacci number to the end of the linked list.
- Handle the edge cases: If the list is empty or has only one element, return the list as there's no need to move any elements.
- Initialize pointers to traverse the list: prev, current, firstFibonacciPrev, and firstFibonacci.
- Traverse the list while checking each element. When you find the first Fibonacci number, store it in firstFibonacci and keep track of its previous node in firstFibonacciPrev.
- Remove the first Fibonacci node from the list by updating the next pointer of its previous node (or the head if it's the first node).
- Traverse to the end of the list using the prev pointer and attach the firstFibonacci node to the end.
- Set the next pointer of the firstFibonacci node to nullptr to indicate it's now the last element in the list.
- Return the updated head of the linked list.
Implementation of the above approach:
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
// Definition for singly-linked list
struct Node {
int val;
Node* next;
Node(int x)
: val(x)
, next(nullptr)
{
}
};
// Function to check if a number
// is a Fibonacci number
bool isFibonacci(int num)
{
if (num == 0 || num == 1) {
return true;
}
int a = 0, b = 1;
while (b < num) {
int temp = b;
b = a + b;
a = temp;
}
return b == num;
}
// Function to move the first Fibonacci number
// to the end of the list
Node* moveFirstFibonacciToEnd(Node* head)
{
// No need to move if the list has 0 or
// 1 elements.
if (!head || !head->next) {
return head;
}
Node* prev = nullptr;
Node* current = head;
Node* firstFibonacciPrev = nullptr;
Node* firstFibonacci = nullptr;
// Find the first Fibonacci number
while (current) {
if (isFibonacci(current->val)) {
firstFibonacciPrev = prev;
firstFibonacci = current;
break;
}
prev = current;
current = current->next;
}
// No Fibonacci number found in the
// list.
if (!firstFibonacci) {
return head;
}
// Remove the first Fibonacci node
// from its position
if (firstFibonacciPrev) {
firstFibonacciPrev->next = firstFibonacci->next;
}
else {
head = firstFibonacci->next;
}
// Move the first Fibonacci node to the end
prev = current;
while (prev->next) {
prev = prev->next;
}
prev->next = firstFibonacci;
firstFibonacci->next = nullptr;
return head;
}
// Function to print the linked list
void printLinkedList(Node* head)
{
while (head) {
cout << head->val << " -> ";
head = head->next;
}
cout << "NULL" << endl;
}
// Drivers code
int main()
{
// Example 1:
Node* head1 = new Node(10);
head1->next = new Node(15);
head1->next->next = new Node(8);
head1->next->next->next = new Node(13);
head1->next->next->next->next = new Node(21);
head1->next->next->next->next->next = new Node(5);
head1->next->next->next->next->next->next = new Node(2);
cout << "Input: ";
printLinkedList(head1);
Node* newHead1 = moveFirstFibonacciToEnd(head1);
cout << "Output: ";
printLinkedList(newHead1);
// Example 2:
Node* head2 = new Node(3);
head2->next = new Node(1);
head2->next->next = new Node(4);
head2->next->next->next = new Node(11);
head2->next->next->next->next = new Node(6);
head2->next->next->next->next->next = new Node(18);
head2->next->next->next->next->next->next
= new Node(24);
cout << "Input: ";
printLinkedList(head2);
Node* newHead2 = moveFirstFibonacciToEnd(head2);
cout << "Output: ";
printLinkedList(newHead2);
return 0;
}
Java
// Java code for moving the first Fibonacci number to the end of a linked list
class Node {
int val;
Node next;
// Constructor for creating a new node with the given value
public Node(int x) {
val = x;
next = null;
}
}
public class MoveFibonacciToEnd {
// Function to check if a number is a Fibonacci number
static boolean isFibonacci(int num) {
if (num == 0 || num == 1) {
return true;
}
int a = 0, b = 1;
while (b < num) {
int temp = b;
b = a + b;
a = temp;
}
return b == num;
}
// Function to move the first Fibonacci number to the end of the list
static Node moveFirstFibonacciToEnd(Node head) {
// No need to move if the list has 0 or 1 elements
if (head == null || head.next == null) {
return head;
}
Node prev = null;
Node current = head;
Node firstFibonacciPrev = null;
Node firstFibonacci = null;
// Find the first Fibonacci number
while (current != null) {
if (isFibonacci(current.val)) {
firstFibonacciPrev = prev;
firstFibonacci = current;
break;
}
prev = current;
current = current.next;
}
// No Fibonacci number found in the list
if (firstFibonacci == null) {
return head;
}
// Remove the first Fibonacci node from its position
if (firstFibonacciPrev != null) {
firstFibonacciPrev.next = firstFibonacci.next;
} else {
head = firstFibonacci.next;
}
// Move the first Fibonacci node to the end
prev = current;
while (prev.next != null) {
prev = prev.next;
}
prev.next = firstFibonacci;
firstFibonacci.next = null;
return head;
}
// Function to print the linked list
static void printLinkedList(Node head) {
while (head != null) {
System.out.print(head.val + " -> ");
head = head.next;
}
System.out.println("NULL");
}
// Driver's code
public static void main(String[] args) {
// Example 1:
Node head1 = new Node(10);
head1.next = new Node(15);
head1.next.next = new Node(8);
head1.next.next.next = new Node(13);
head1.next.next.next.next = new Node(21);
head1.next.next.next.next.next = new Node(5);
head1.next.next.next.next.next.next = new Node(2);
System.out.print("Input: ");
printLinkedList(head1);
Node newHead1 = moveFirstFibonacciToEnd(head1);
System.out.print("Output: ");
printLinkedList(newHead1);
// Example 2:
Node head2 = new Node(3);
head2.next = new Node(1);
head2.next.next = new Node(4);
head2.next.next.next = new Node(11);
head2.next.next.next.next = new Node(6);
head2.next.next.next.next.next = new Node(18);
head2.next.next.next.next.next.next = new Node(24);
System.out.print("Input: ");
printLinkedList(head2);
Node newHead2 = moveFirstFibonacciToEnd(head2);
System.out.print("Output: ");
printLinkedList(newHead2);
}
}
Python3
class Node:
def __init__(self, x):
self.val = x
self.next = None
def is_fibonacci(num):
if num == 0 or num == 1:
return True
a, b = 0, 1
while b < num:
temp = b
b = a + b
a = temp
return b == num
def move_first_fibonacci_to_end(head):
# No need to move if the list has 0 or 1 elements.
if not head or not head.next:
return head
prev = None
current = head
first_fibonacci_prev = None
first_fibonacci = None
# Find the first Fibonacci number
while current:
if is_fibonacci(current.val):
first_fibonacci_prev = prev
first_fibonacci = current
break
prev = current
current = current.next
# No Fibonacci number found in the list.
if not first_fibonacci:
return head
# Remove the first Fibonacci node from its position
if first_fibonacci_prev:
first_fibonacci_prev.next = first_fibonacci.next
else:
head = first_fibonacci.next
# Move the first Fibonacci node to the end
prev = current
while prev.next:
prev = prev.next
prev.next = first_fibonacci
first_fibonacci.next = None
return head
def print_linked_list(head):
while head:
print(head.val, end=" -> ")
head = head.next
print("NULL")
# Driver Code
if __name__ == "__main__":
# Example 1
head1 = Node(10)
head1.next = Node(15)
head1.next.next = Node(8)
head1.next.next.next = Node(13)
head1.next.next.next.next = Node(21)
head1.next.next.next.next.next = Node(5)
head1.next.next.next.next.next.next = Node(2)
print("Input:", end=" ")
print_linked_list(head1)
new_head1 = move_first_fibonacci_to_end(head1)
print("Output:", end=" ")
print_linked_list(new_head1)
# Example 2
head2 = Node(3)
head2.next = Node(1)
head2.next.next = Node(4)
head2.next.next.next = Node(11)
head2.next.next.next.next = Node(6)
head2.next.next.next.next.next = Node(18)
head2.next.next.next.next.next.next = Node(24)
print("Input:", end=" ")
print_linked_list(head2)
new_head2 = move_first_fibonacci_to_end(head2)
print("Output:", end=" ")
print_linked_list(new_head2)
# This code is contributed by shivamgupta0987654321
C#
using System;
public class Node
{
public int val;
public Node next;
public Node(int x)
{
val = x;
next = null;
}
}
public class LinkedListOperations
{
public static bool IsFibonacci(int num)
{
if (num == 0 || num == 1)
return true;
int a = 0, b = 1;
while (b < num)
{
int temp = b;
b = a + b;
a = temp;
}
return b == num;
}
public static Node MoveFirstFibonacciToEnd(Node head)
{
// No need to move if the list has 0 or 1 elements.
if (head == null || head.next == null)
return head;
Node prev = null;
Node current = head;
Node firstFibonacciPrev = null;
Node firstFibonacci = null;
// Find the first Fibonacci number
while (current != null)
{
if (IsFibonacci(current.val))
{
firstFibonacciPrev = prev;
firstFibonacci = current;
break;
}
prev = current;
current = current.next;
}
// No Fibonacci number found in the list.
if (firstFibonacci == null)
return head;
// Remove the first Fibonacci node from its position
if (firstFibonacciPrev != null)
firstFibonacciPrev.next = firstFibonacci.next;
else
head = firstFibonacci.next;
// Move the first Fibonacci node to the end
prev = current;
while (prev.next != null)
prev = prev.next;
prev.next = firstFibonacci;
firstFibonacci.next = null;
return head;
}
public static void PrintLinkedList(Node head)
{
while (head != null)
{
Console.Write(head.val + " -> ");
head = head.next;
}
Console.WriteLine("NULL");
}
// Driver Code
public static void Main(string[] args)
{
// Example 1
Node head1 = new Node(10);
head1.next = new Node(15);
head1.next.next = new Node(8);
head1.next.next.next = new Node(13);
head1.next.next.next.next = new Node(21);
head1.next.next.next.next.next = new Node(5);
head1.next.next.next.next.next.next = new Node(2);
Console.Write("Input: ");
PrintLinkedList(head1);
Node newHead1 = MoveFirstFibonacciToEnd(head1);
Console.Write("Output: ");
PrintLinkedList(newHead1);
// Example 2
Node head2 = new Node(3);
head2.next = new Node(1);
head2.next.next = new Node(4);
head2.next.next.next = new Node(11);
head2.next.next.next.next = new Node(6);
head2.next.next.next.next.next = new Node(18);
head2.next.next.next.next.next.next = new Node(24);
Console.Write("Input: ");
PrintLinkedList(head2);
Node newHead2 = MoveFirstFibonacciToEnd(head2);
Console.Write("Output: ");
PrintLinkedList(newHead2);
}
}
JavaScript
class Node {
constructor(x) {
this.val = x;
this.next = null;
}
}
// Function to check if a number is a Fibonacci number
function isFibonacci(num) {
if (num === 0 || num === 1) {
return true;
}
let a = 0, b = 1;
while (b < num) {
const temp = b;
b = a + b;
a = temp;
}
return b === num;
}
// Function to move the first Fibonacci number to the end of the linked list
function moveFirstFibonacciToEnd(head) {
if (!head || !head.next) {
return head; // Return if the list has 0 or 1 elements
}
let prev = null;
let current = head;
let firstFibonacciPrev = null;
let firstFibonacci = null;
// Find the first Fibonacci number in the linked list
while (current) {
if (isFibonacci(current.val)) {
firstFibonacciPrev = prev;
firstFibonacci = current;
break;
}
prev = current;
current = current.next;
}
if (!firstFibonacci) {
return head; // If no Fibonacci number found, return the original list
}
// Remove the first Fibonacci node from its position
if (firstFibonacciPrev) {
firstFibonacciPrev.next = firstFibonacci.next;
} else {
head = firstFibonacci.next;
}
// Move the first Fibonacci node to the end of the list
prev = current;
while (prev.next) {
prev = prev.next;
}
prev.next = firstFibonacci;
firstFibonacci.next = null;
return head; // Return the updated head of the list
}
// Function to print the linked list
function printLinkedList(head) {
while (head) {
process.stdout.write(head.val + " -> ");
head = head.next;
}
console.log("NULL");
}
// Driver Code
if (require.main === module) {
// Example 1
const head1 = new Node(10);
head1.next = new Node(15);
head1.next.next = new Node(8);
head1.next.next.next = new Node(13);
head1.next.next.next.next = new Node(21);
head1.next.next.next.next.next = new Node(5);
head1.next.next.next.next.next.next = new Node(2);
process.stdout.write("Input: ");
printLinkedList(head1);
const newHead1 = moveFirstFibonacciToEnd(head1);
process.stdout.write("Output: ");
printLinkedList(newHead1);
// Example 2
const head2 = new Node(3);
head2.next = new Node(1);
head2.next.next = new Node(4);
head2.next.next.next = new Node(11);
head2.next.next.next.next = new Node(6);
head2.next.next.next.next.next = new Node(18);
head2.next.next.next.next.next.next = new Node(24);
process.stdout.write("Input: ");
printLinkedList(head2);
const newHead2 = moveFirstFibonacciToEnd(head2);
process.stdout.write("Output: ");
printLinkedList(newHead2);
}
OutputInput: 10 -> 15 -> 8 -> 13 -> 21 -> 5 -> 2 -> NULL
Output: 10 -> 15 -> 13 -> 21 -> 5 -> 2 -> 8 -> NULL
Input: 3 -> 1 -> 4 -> 11 -> 6 -> 18 -> 24 -> NULL
Output: 1 -> 4 -> 11 -> 6 -> 18 -> 24 -> 3 -> N...
Time Complexity: O(n), where n is the number of nodes in the list.
Auxiliary Space: O(1) because it uses a constant amount of extra space.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem