Open In App

Double a Number Represented in a Linked List

Given a non-empty linked list representing a non-negative integer without leading zeroes the task is to double the value of whole linked list like(2->3->1 then answer will be 4->6->2) and print the resultant linked list.

Examples:

Input: head = [2, 0, 9]
Output: [4, 1, 8]
Explanation: Given linked list represents the number 209, Hence the returned linked list represents the number 209* 2 = 418.

Input: head = [8, 9, 1]
Output: [1, 7, 8, 2]
Explanation: Given linked list represents the number 891, Hence the returned linked list represents the number 891 * 2 = 1782.

Approach:

To double the value represented as a linked list, firstly we will reverse the original linked list. Now, traverse over the linked list and multiply the value at each node with 2. After multiplying if the value exceeds 9, then keep track of the ten's digit using carry. After traversing over all the nodes, reverse the resultant string to get the final answer.

Step by step algorithm:

Below is the code implementation of the above approach:-

#include <iostream>
using namespace std;

// ListNode class representing each node in the linked list
class ListNode {
public:
    // Value of the node
    int data;
    // Reference to the next node
    ListNode* next;

    // Constructor to initialize ListNode with a given value
    ListNode(int val)
        : data(val)
        , next(nullptr)
    {
    }
};

// Function to reverse a linked list
ListNode* reverse(ListNode* head)
{
    // Current node
    ListNode* curr = head;
    // Previous node
    ListNode* prev = nullptr;
    // Next node
    ListNode* nextNode = nullptr;
    while (curr != nullptr) {
        // Store next node
        nextNode = curr->next;
        // Reverse current node's pointer
        curr->next = prev;
        // Move previous to current
        prev = curr;
        // Move current to next
        curr = nextNode;
    }
    // Return new head of reversed list
    return prev;
}

// Function to double the value of each node in a linked
// list
ListNode* doubleLL(ListNode* head)
{
    // Reverse the linked list
    ListNode* reversedHead = reverse(head);
    // Carry for addition
    int carry = 0;
    // Dummy node for result list
    ListNode* result = new ListNode(-1);
    // Pointer to the result list
    ListNode* resultPtr = result;

    // Traverse the reversed list and double each node's
    // value
    while (reversedHead != nullptr) {
        // Calculate sum with carry and doubled value
        int sum = carry + (reversedHead->data * 2);
        // Create a new node with the unit's place of sum
        ListNode* temp = new ListNode(sum % 10);
        // Connect the new node to the result list
        resultPtr->next = temp;
        // Move result pointer to the newly added node
        resultPtr = temp;
        // Update carry for the next addition
        carry = sum / 10;
        // Move to the next node in the reversed list
        reversedHead = reversedHead->next;
    }

    // If there's a carry remaining, add it as a new node
    if (carry != 0) {
        // Create a new node with the carry value
        ListNode* temp = new ListNode(carry);
        // Connect it to the result list
        resultPtr->next = temp;
        // Move result pointer to the newly added node
        resultPtr = temp;
    }
    // Reverse the result list and return its head
    return reverse(result->next);
}

// Main method to test the code
int main()
{
    // Create a linked list with initial value 1
    ListNode* head = new ListNode(2);
    // Add a node with value 8
    ListNode* h1 = new ListNode(0);
    // Connect it to the first node
    head->next = h1;
    // Add a node with value 9
    ListNode* h2 = new ListNode(9);
    // Connect it to the second node
    h1->next = h2;
    // Double the values of the linked list
    ListNode* result = doubleLL(head);
    // Print the values of the resulting linked list
    while (result != nullptr) {
        cout << result->data << " ";
        result = result->next;
    }

    return 0;
}

// This code is contributed by shivamgupta310570
import java.io.*;

class GFG {
    // ListNode class representing each node in the linked
    // list
    public static class ListNode {
        // Value of the node
        int data;
        // Reference to the next node
        ListNode next;

        // Constructor to initialize ListNode with a given
        // value
        ListNode(int val) { this.data = val; }
    }

    // Function to reverse a linked list
    public static ListNode reverse(ListNode head)
    {
        // Current node
        ListNode curr = head;
        // Previous node
        ListNode prev = null;
        // Next node
        ListNode nextNode = null;
        while (curr != null) {
            // Store next node
            nextNode = curr.next;
            // Reverse current node's pointer
            curr.next = prev;
            // Move previous to current
            prev = curr;
            // Move current to next
            curr = nextNode;
        }
        // Return new head of reversed list
        return prev;
    }

    // Function to double the value of each node in a linked
    // list
    public static ListNode doubleLL(ListNode head)
    {
        // Reverse the linked list
        ListNode reversedHead = reverse(head);
        // Carry for addition
        int carry = 0;
        // Dummy node for result list
        ListNode result = new ListNode(-1);
        // Pointer to the result list
        ListNode resultPtr = result;

        // Traverse the reversed list and double each node's
        // value
        while (reversedHead != null) {
            // Calculate sum with carry and doubled value
            int sum = carry + (reversedHead.data * 2);
            // Create a new node with the unit's place of
            // sum
            ListNode temp = new ListNode(sum % 10);
            // Connect the new node to the result list
            resultPtr.next = temp;
            // Move result pointer to the newly added node
            resultPtr = temp;
            // Update carry for the next addition
            carry = sum / 10;
            // Move to the next node in the reversed list
            reversedHead = reversedHead.next;
        }

        // If there's a carry remaining, add it as a new
        // node
        if (carry != 0) {
            // Create a new node with the carry value
            ListNode temp = new ListNode(carry);
            // Connect it to the result list
            resultPtr.next = temp;
            // Move result pointer to the newly added node
            resultPtr = temp;
        }
        // Reverse the result list and return its head
        return reverse(result.next);
    }

    // Main method to test the code
    public static void main(String[] args)
    {
        // Create a linked list with initial value 1
        ListNode head = new ListNode(2);
        // Add a node with value 8
        ListNode h1 = new ListNode(0);
        // Connect it to the first node
        head.next = h1;
        // Add a node with value 9
        ListNode h2 = new ListNode(9);
        // Connect it to the second node
        h1.next = h2;
        // Double the values of the linked list
        ListNode result = doubleLL(head);
        // Print the values of the resulting linked list
        while (result != null) {
            System.out.print(result.data + " ");
            result = result.next;
        }
    }
}
# ListNode class representing each node in the linked list
class ListNode:
    def __init__(self, val):
        # Value of the node
        self.data = val
        # Reference to the next node
        self.next = None

# Function to reverse a linked list


def reverse(head):
    # Current node
    curr = head
    # Previous node
    prev = None
    # Next node
    nextNode = None
    while curr is not None:
        # Store next node
        nextNode = curr.next
        # Reverse current node's pointer
        curr.next = prev
        # Move previous to current
        prev = curr
        # Move current to next
        curr = nextNode
    # Return new head of reversed list
    return prev

# Function to double the value of each node in a linked list


def doubleLL(head):
    # Reverse the linked list
    reversedHead = reverse(head)
    # Carry for addition
    carry = 0
    # Dummy node for result list
    result = ListNode(-1)
    # Pointer to the result list
    resultPtr = result

    # Traverse the reversed list and double each node's value
    while reversedHead is not None:
        # Calculate sum with carry and doubled value
        sum_val = carry + (reversedHead.data * 2)
        # Create a new node with the unit's place of sum
        temp = ListNode(sum_val % 10)
        # Connect the new node to the result list
        resultPtr.next = temp
        # Move result pointer to the newly added node
        resultPtr = temp
        # Update carry for the next addition
        carry = sum_val // 10
        # Move to the next node in the reversed list
        reversedHead = reversedHead.next

    # If there's a carry remaining, add it as a new node
    if carry != 0:
        # Create a new node with the carry value
        temp = ListNode(carry)
        # Connect it to the result list
        resultPtr.next = temp
        # Move result pointer to the newly added node
        resultPtr = temp
    # Reverse the result list and return its head
    return reverse(result.next)


# Main method to test the code
if __name__ == "__main__":
    # Create a linked list with initial value 1
    head = ListNode(2)
    # Add a node with value 8
    h1 = ListNode(0)
    # Connect it to the first node
    head.next = h1
    # Add a node with value 9
    h2 = ListNode(9)
    # Connect it to the second node
    h1.next = h2
    # Double the values of the linked list
    result = doubleLL(head)
    # Print the values of the resulting linked list
    while result is not None:
        print(result.data, end=" ")
        result = result.next
# this code is contributed by Utkarsh.

Output
3 7 8 

Time Complexity: O(N), where N is the number of elements in the linked list.
Auxiliary Space: O(N)

Article Tags :