Multiply a single digit number in place to a number represented as a Linked List | C ++ program for the above approach ; Node of a Linked List ; Function to create a new node with given data ; Initialize new node ; Set the data field of the node ; Return the new node ; Function to reverse the linked list ; Traverse until curr != null ; Return the head of the reversed linked list ; Utility function to multiply a single digit to a linked list ; Store the head of list ; Stores the address of previous node ; Initially set carry as 0 and product as 1 ; Multiply M with each digit ; Add carry to product if carry exist ; Update carry for next calculation ; Update the value of each nodes ; Move head and temp pointers to next nodes ; If some carry is still there , add a new node to list ; Return head of the resultant list ; Function to multiply a single digit to a linked list ; Reverse linked list ; Multiply M from left to right of reversed list ; Reverse the modified list and return its head ; Function to print the linked list ; Driver Code ; Given Input list : 1 -> 2 -> 7 -> 3 ; Function Call ; Print resultant list
#include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * next ; } ; Node * newNode ( int data ) { Node * new_node = new Node ; new_node -> data = data ; new_node -> next = NULL ; return new_node ; } Node * reverse ( Node * head ) { Node * prev = NULL ; Node * current = head ; Node * next ; while ( current != NULL ) { next = current -> next ; current -> next = prev ; prev = current ; current = next ; } return prev ; } Node * multiplyHelp ( Node * head , int M ) { Node * res = head ; Node * prev = NULL ; int carry = 0 , product = 1 ; while ( head != NULL ) { product = head -> data * M ; product += carry ; carry = product / 10 ; head -> data = product % 10 ; prev = head ; head = head -> next ; } if ( carry > 0 ) prev -> next = newNode ( carry ) ; return res ; } Node * multiply ( Node * head , int M ) { head = reverse ( head ) ; head = multiplyHelp ( head , M ) ; return reverse ( head ) ; } void printList ( Node * node ) { while ( node != NULL ) { cout << node -> data ; node = node -> next ; } } int main ( ) { Node * head = newNode ( 1 ) ; head -> next = newNode ( 2 ) ; head -> next -> next = newNode ( 7 ) ; head -> next -> next -> next = newNode ( 3 ) ; int M = 3 ; head = multiply ( head , M ) ; printList ( head ) ; return 0 ; }