Horje
Inserting GCD between adjacent nodes of linked list

Given a linked list, in which each node contains an integer value, Between every adjacent pair of nodes insert a new node with a value equal to the greatest common divisor of them.

Examples:

Input: Linked List = 30 -> 6 -> 14 -> 3 -> NULL
Output: 30 -> 6 -> 6 -> 2 -> 14 -> 1 -> 3 -> NULL

Explanation:

  • We insert the greatest common divisor of 30 and 6 = 6 between the 1st and the 2nd node.
  • We insert the greatest common divisor of 6 and 14 = 2 between the 2nd and the 3rd node.
  • We insert the greatest common divisor of 14 and 3 = 1 between the 3rd and the 4th node.

There are no more adjacent nodes, so we return the linked list.

Input: Linked List = 3 -> NULL
Output: 3 -> NULL
Explanation: There are no pairs of adjacent nodes, so we return the initial linked list as it is.

Approach:

We can solve this problem by traversing the linked list and keeping track of previous node and each step insert a new node which represents the GCD of current node and previous node.

Step-by-step algorithm:

  • Check for Base Cases: If the linked list is empty or has only one node, return the list as it is.
  • Initialize Variables:
    • prev is initialized to null as there’s no previous node initially.
    • curr is initialized to the head of the list.
    • n is initialized to the next node after curr.
  • Iterate Through the List:
    • Use a while loop to iterate over the list until n becomes null.
  • Within the loop:
    • Calculate the GCD of curr.data and n.data using the gcd method.
    • Create a new ListNode called temp with the GCD value.
    • Set prev.next to point to temp, linking the previous node to the new node containing the GCD.
    • Set temp.next to point to curr, linking the new node to the next node in the original list.
    • Update prev, curr, and n to move one step forward in the list.
  • Return the Modified List: After the loop, return the head of the modified list.

Below is the implementation of the above algorithm:

C++
#include <iostream>
using namespace std;

// Structure of a Node
struct ListNode {
    int data;
    ListNode* next;
    ListNode(int data) : data(data), next(nullptr) {}
};

// Euclidean function for GCD Calculation
int gcd(int x, int y) {
    if (y == 0)
        return x;
    return gcd(y, x % y);
}

// Insertion of GCD
ListNode* insertGreatestCommonDivisors(ListNode* head) {
    // Base Case
    if (head == nullptr || head->next == nullptr)
        return head;

    // Variable initialization
    ListNode* prev = nullptr;
    ListNode* curr = head;
    ListNode* n = curr->next;

    // Traversing linked list and simultaneously
    // inserting new node having gcd of both nodes
    while (n != nullptr) {
        int val = gcd(curr->data, n->data);
        ListNode* temp = new ListNode(val);
        prev = curr;
        curr = n;
        n = n->next;
        temp->next = curr;
        prev->next = temp;
    }
    return head;
}

// Driver Function
int main() {
    // Creating a linked list
    ListNode* head = new ListNode(30);
    head->next = new ListNode(6);
    head->next->next = new ListNode(14);
    head->next->next->next = new ListNode(3);

    // Function call for operation
    ListNode* ans = insertGreatestCommonDivisors(head);
    ListNode* temp = ans;

    // Traversing the final linked list
    while (temp != nullptr) {
        cout << temp->data << " ";
        temp = temp->next;
    }
    return 0;
}
// This code is contributed by shivamgupta0987654321
Java
/*package whatever //do not write package name here */

import java.io.*;

class GFG {

    // Structure of a Node
    public static class ListNode {
        int data;
        ListNode next;
        ListNode(int data) { this.data = data; }
    }

    // Euclidean function for GCD Calculation
    public static int gcd(int x, int y)
    {
        if (y == 0)
            return x;
        return gcd(y, x % y);
    }

    // Insertion of GCD
    public static ListNode
    insertGreatestCommonDivisors(ListNode head)
    {

        // Base Case
        if (head == null || head.next == null)
            return head;

        // Variable initialization
        ListNode prev = null;
        ListNode curr = head;
        ListNode n = curr.next;

        // Traversing linked list and simultaniously
        // inserting new node having gcd of both nodes
        while (n != null) {
            int val = gcd(curr.data, n.data);
            ListNode temp = new ListNode(val);
            prev = curr;
            curr = n;
            n = n.next;
            temp.next = curr;
            prev.next = temp;
        }
        return head;
    }

    // Driver Function
    public static void main(String[] args)
    {

        // Creating a linked list
        ListNode head = new ListNode(30);
        head.next = new ListNode(6);
        head.next.next = new ListNode(14);
        head.next.next.next = new ListNode(3);

        // Function call for operation
        ListNode ans = insertGreatestCommonDivisors(head);
        ListNode temp = ans;

        // Traversing the final linked list
        while (temp != null) {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
    }
}
Python3
class ListNode:
    def __init__(self, data):
        self.data = data
        self.next = None

def gcd(x, y):
    while y != 0:
        x, y = y, x % y
    return x

def insertGreatestCommonDivisors(head):
    if head is None or head.next is None:
        return head

    prev = None
    curr = head
    n = curr.next

    while n is not None:
        val = gcd(curr.data, n.data)
        temp = ListNode(val)
        prev = curr
        curr = n
        n = n.next
        temp.next = curr
        prev.next = temp

    return head

def printLinkedList(head):
    temp = head
    while temp is not None:
        print(temp.data, end=" ")
        temp = temp.next

# Creating the linked list
head = ListNode(30)
head.next = ListNode(6)
head.next.next = ListNode(14)
head.next.next.next = ListNode(3)

# Function call for operation
ans = insertGreatestCommonDivisors(head)

# Printing the final linked list
printLinkedList(ans)
JavaScript
// Structure of a Node
class ListNode {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

// Euclidean function for GCD Calculation
function gcd(x, y) {
    if (y === 0)
        return x;
    return gcd(y, x % y);
}

// Insertion of GCD
function insertGreatestCommonDivisors(head) {
    // Base Case
    if (head === null || head.next === null)
        return head;

    // Variable initialization
    let prev = null;
    let curr = head;
    let n = curr.next;

    // Traversing linked list and simultaneously
    // inserting new node having gcd of both nodes
    while (n !== null) {
        let val = gcd(curr.data, n.data);
        let temp = new ListNode(val);
        prev = curr;
        curr = n;
        n = n.next;
        temp.next = curr;
        prev.next = temp;
    }
    return head;
}

// Driver Function
function main() {
    // Creating a linked list
    let head = new ListNode(30);
    head.next = new ListNode(6);
    head.next.next = new ListNode(14);
    head.next.next.next = new ListNode(3);

    // Function call for operation
    let ans = insertGreatestCommonDivisors(head);
    let temp = ans;

    // Collecting output in a string
    let output = "";
    while (temp !== null) {
        output += temp.data + " ";
        temp = temp.next;
    }

    // Printing the output in a single line
    console.log(output.trim());
}

// Call the main function to execute
main();

Output
30 6 6 2 14 1 3 

Time Complexity: O(nlog(x)) , where n is number of nodes in linked list and x is the maximum value of any node.
Auxiliary Space Complexity:– O(1).




Reffered: https://www.geeksforgeeks.org


DSA

Related
Singly Linked List in Python Singly Linked List in Python
Doubly Linked List in Python Doubly Linked List in Python
Graph Coloring Algorithm in Python Graph Coloring Algorithm in Python
Circular Linked List in Python Circular Linked List in Python
Finding Composite Sum Permutation Finding Composite Sum Permutation

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14