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
Move the Kth Largest Fibonacci Number Node to the End of a Singly Linked List
Given a singly linked list containing integer values. The task is to find the Kth largest Fibonacci number within this list and move it to the end of the list. Examples: Input: 12 -> 11 -> 0 -> 5 -> 8 -> 13 -> 17 -> 21 -> NULL, K = 3Output: 12 -> 11 -> 0 -> 5 -> 1
12 min read
Move the Kth Prime Number Node to the End of the Linked List
Given a singly linked list, the task is to move the Kth prime number node to the end of the list while preserving the order of other nodes. Examples: Input: 4 -> 7 -> 11 -> 3 -> 14 -> 2 -> NULL, K = 2Output: 4 -> 7 -> 3 -> 14 -> 2 -> 11 -> NULLExplanation: In the
13 min read
Move the Kth element to the Front of a Doubly Linked List
Given a doubly linked list and an integer K, you need to move the Kth element to the front of the list while maintaining the order of the other elements. Examples: Input: DLL: 2 <-> 6 <-> 3 <-> 8 <-> 11 <-> 23 <-> 7 -> NULL, K = 4Output: 8 <-> 2 <->
11 min read
Move all zeros to the front of the linked list
Given a linked list. the task is to move all 0's to the front of the linked list. The order of all other elements except 0 should be the same after rearrangement. Examples: Input : 0 1 0 1 2 0 5 0 4 0 Output :0 0 0 0 0 1 1 2 5 4 Input :1 1 2 3 0 0 0 Output :0 0 0 1 1 2 3Recommended PracticeMove all
11 min read
Minimum number of Fibonacci jumps to reach end
Given an array of 0s and 1s, If any particular index i has value 1 then it is a safe index and if the value is 0 then it is an unsafe index. A man is standing at index -1(source) can only land on a safe index and he has to reach the Nth index (last position). At each jump, the man can only travel a
11 min read
Append the last M nodes to the beginning of the given linked list.
Given a linked list and an integer M, the task is to append the last M nodes of the linked list to the front.Examples: Input: List = 4 -> 5 -> 6 -> 1 -> 2 -> 3 -> NULL, M = 3 Output: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULLInput: List = 8 -> 7 -> 0 -> 4 -> 1
13 min read
XOR Linked List - Find Nth Node from the end
Given a XOR linked list and an integer N, the task is to print the Nth node from the end of the given XOR linked list. Examples: Input: 4 â> 6 â> 7 â> 3, N = 1 Output: 3 Explanation: 1st node from the end is 3.Input: 5 â> 8 â> 9, N = 4 Output: Wrong Input Explanation: The given Xor Li
15+ min read
Replace every node in linked list with its closest fibonacci number
Given a singly linked list of integers, the task is to replace every node with its closest Fibonacci number and return the modified linked list. Examples: Input: List: 3->5->9->12->13->15->nullOutput: 3->5->8->13->13->13->nullExplanation: The closest Fibonacci num
8 min read
Find the numbers present at Kth level of a Fibonacci Binary Tree
Given a number K, the task is to print the fibonacci numbers present at Kth level of a Fibonacci Binary Tree.Examples: Input: K = 3 Output: 2, 3, 5, 8 Explanation: Fibonacci Binary Tree for 3 levels: 0 / \ 1 1 /\ / \ 2 3 5 8 Numbers present at level 3: 2, 3, 5, 8 Input: K = 2 Output: 1, 1 Explanatio
12 min read
Move the Kth Element in a Doubly Linked List to the End
Given a doubly linked list and an integer K, you need to move the Kth element to the end of the list while maintaining the order of the other elements. Examples: Input: DLL: 2 <-> 6 <-> 3 <-> 8 <-> 11 <-> 23 <-> 7 -> NULL, K = 1Output: 6 <-> 3 <-> 8
13 min read