Add number and its reverse represented by Linked List
Last Updated : 23 Mar, 2023
Given a number represented by a linked list, write a function that returns the sum of that number with its reverse form, and returns the resultant linked list.
Note: Avoid modifying the original linked list.
Examples:
Input: 1->2->3->4
Output: 5->5->5->5
Explanation:
Input list: 1 2 3 4
Reverse list: + 4 3 2 1
resultant list: 5 5 5 5
Input: 4->7->3->6
Output: 1->1->1->1->0
Explanation:
Input list: 4 7 3 6
reverse list: + 6 3 7 4
resultant list: 1 1 1 1 0
Approach: The approach to solve the problem of adding linked lists and its reverse can be divided into the following steps:
- Make a copy of the given linked list: To avoid modifying the original linked list, a copy of it is created.
- Reverse the linked list: The reversed linked list is obtained by iteratively changing the next pointer of each node to point to the previous node.
- Add the linked list and its reverse: The two linked lists (original linked list and its reverse) are added digit by digit, starting from the least significant digit. A carry variable is maintained while adding the digits.
- Reverse the result of the addition: The result of the addition, which is in reverse order, is reversed back to obtain the final result.
- Print the resultant linked list: The final resultant linked list is printed.
Below is the implementation of this approach.
C++ // C++ code of above approach #include <bits/stdc++.h> using namespace std; // Define the structure of a // node in the linked list struct Node { int data; struct Node* next; Node(int x) { data = x; next = NULL; } }; // Function to return the // reverse of a linked list Node* reverseList(Node* head) { Node* prev = NULL; Node* cur = head; Node* next_ = NULL; while (cur != NULL) { next_ = cur->next; cur->next = prev; prev = cur; cur = next_; } return prev; } // Function to return the sum of two // linked lists Node* addTwoLists(Node* l1, Node* l2) { Node* dummy = new Node(0); Node* cur = dummy; int carry = 0; while (l1 != NULL || l2 != NULL) { int x = l1 ? l1->data : 0; int y = l2 ? l2->data : 0; int sum = carry + x + y; carry = sum / 10; cur->next = new Node(sum % 10); cur = cur->next; if (l1) { l1 = l1->next; } if (l2) { l2 = l2->next; } } if (carry > 0) { cur->next = new Node(carry); } return dummy->next; } // Function to print a linked list void printList(Node* head) { while (head != NULL) { cout << head->data << " "; head = head->next; } cout << endl; } // Function to create a copy of // a linked list Node* copyList(Node* head) { Node* cur = head; Node* dummy = new Node(0); Node* copy = dummy; while (cur != NULL) { copy->next = new Node(cur->data); copy = copy->next; cur = cur->next; } return dummy->next; } // Driver Code int main() { // Example linked list: // 1 -> 2 -> 3 -> 4 Node* head1 = new Node(1); head1->next = new Node(2); head1->next->next = new Node(3); head1->next->next->next = new Node(4); // Printing original linked list cout << "Original linked list : "; printList(head1); // Step1 - Make a copy of original // linked list Node* newList = copyList(head1); // Step2 - Reverse a linked list Node* head2 = reverseList(newList); // Printing reversed linked list cout << "Reversed linked list : "; printList(head2); // Step3 - Addition of a original // linked list and its reverse Node* addition = addTwoLists(head1, head2); // Step4 - Reverse a addition // Linked list Node* result = reverseList(addition); // Step5 - Print the resultant // linked list cout << "Resultant linked list : "; printList(result); return 0; }
Java // Java code implementation for the above approach import java.io.*; import java.util.*; // Define the structure of a node in the linked list class Node { int data; Node next; Node(int x) { data = x; next = null; } } class GFG { // Function to return the reverse of a linked list static Node reverseList(Node head) { Node prev = null; Node cur = head; Node next_; while (cur != null) { next_ = cur.next; cur.next = prev; prev = cur; cur = next_; } return prev; } // Function to return the sum of two linked lists static Node addTwoLists(Node l1, Node l2) { Node dummy = new Node(0); Node cur = dummy; int carry = 0; while (l1 != null || l2 != null) { int x = l1 != null ? l1.data : 0; int y = l2 != null ? l2.data : 0; int sum = carry + x + y; carry = sum / 10; cur.next = new Node(sum % 10); cur = cur.next; if (l1 != null) { l1 = l1.next; } if (l2 != null) { l2 = l2.next; } } if (carry > 0) { cur.next = new Node(carry); } return dummy.next; } // Function to print a linked list static void printList(Node head) { while (head != null) { System.out.print(head.data + " "); head = head.next; } System.out.println(); } // Function to create a copy of a linked list static Node copyList(Node head) { Node cur = head; Node dummy = new Node(0); Node copy = dummy; while (cur != null) { copy.next = new Node(cur.data); copy = copy.next; cur = cur.next; } return dummy.next; } public static void main(String[] args) { // Example linked list: // 1 -> 2 -> 3 -> 4 Node head1 = new Node(1); head1.next = new Node(2); head1.next.next = new Node(3); head1.next.next.next = new Node(4); // Printing original linked list System.out.print("Original linked list : "); printList(head1); // Step1 - Make a copy of original linked list Node newList = copyList(head1); // Step2 - Reverse a linked list Node head2 = reverseList(newList); // Printing reversed linked list System.out.print("Reversed linked list : "); printList(head2); // Step3 - Addition of a original linked list and // its reverse Node addition = addTwoLists(head1, head2); // Step4 - Reverse a addition Linked list Node result = reverseList(addition); // Step5 - Print the resultant linked list System.out.print("Resultant linked list : "); printList(result); } } // This code is contributed by sankar
Python3 # python code of above approach # Define the structure of a # node in the linked list class Node: def __init__(self, x): self.data = x self.next = None # Function to return the # reverse of a linked list def reverseList(head): prev = None cur = head next_ = None while cur is not None: next_ = cur.next cur.next = prev prev = cur cur = next_ return prev # Function to return the sum of two # linked lists def addTwoLists(l1, l2): dummy = Node(0) cur = dummy carry = 0 while l1 is not None or l2 is not None: x = l1.data if l1 else 0 y = l2.data if l2 else 0 summ = carry + x + y carry = summ // 10 cur.next = Node(summ % 10) cur = cur.next if l1: l1 = l1.next if l2: l2 = l2.next if carry > 0: cur.next = Node(carry) return dummy.next # Function to print a linked list def printList(head): while head is not None: print(head.data, end=" ") head = head.next print() # Function to create a copy of # a linked list def copyList(head): cur = head dummy = Node(0) copy = dummy while cur is not None: copy.next = Node(cur.data) copy = copy.next cur = cur.next return dummy.next # Driver Code if __name__ == '__main__': # Example linked list: # 1 -> 2 -> 3 -> 4 head1 = Node(1) head1.next = Node(2) head1.next.next = Node(3) head1.next.next.next = Node(4) # Printing original linked list print("Original linked list : ", end="") printList(head1) # Step1 - Make a copy of original # linked list newList = copyList(head1) # Step2 - Reverse a linked list head2 = reverseList(newList) # Printing reversed linked list print("Reversed linked list : ", end="") printList(head2) # Step3 - Addition of a original # linked list and its reverse addition = addTwoLists(head1, head2) # Step4 - Reverse a addition # Linked list result = reverseList(addition) # Step5 - Print the resultant # linked list print("Resultant linked list : ", end="") printList(result)
C# // C# code implementation for the above approach using System; // Define the structure of a node in the linked list public class Node { public int data; public Node next; public Node(int x) { data = x; next = null; } } public class GFG { // Function to return the reverse of a linked list static Node reverseList(Node head) { Node prev = null; Node cur = head; Node next_; while (cur != null) { next_ = cur.next; cur.next = prev; prev = cur; cur = next_; } return prev; } // Function to return the sum of two linked lists static Node addTwoLists(Node l1, Node l2) { Node dummy = new Node(0); Node cur = dummy; int carry = 0; while (l1 != null || l2 != null) { int x = l1 != null ? l1.data : 0; int y = l2 != null ? l2.data : 0; int sum = carry + x + y; carry = sum / 10; cur.next = new Node(sum % 10); cur = cur.next; if (l1 != null) { l1 = l1.next; } if (l2 != null) { l2 = l2.next; } } if (carry > 0) { cur.next = new Node(carry); } return dummy.next; } // Function to print a linked list static void printList(Node head) { while (head != null) { Console.Write(head.data + " "); head = head.next; } Console.WriteLine(); } // Function to create a copy of a linked list static Node copyList(Node head) { Node cur = head; Node dummy = new Node(0); Node copy = dummy; while (cur != null) { copy.next = new Node(cur.data); copy = copy.next; cur = cur.next; } return dummy.next; } static public void Main() { // Code // Example linked list: // 1 -> 2 -> 3 -> 4 Node head1 = new Node(1); head1.next = new Node(2); head1.next.next = new Node(3); head1.next.next.next = new Node(4); // Printing original linked list Console.Write("Original linked list : "); printList(head1); // Step1 - Make a copy of original linked list Node newList = copyList(head1); // Step2 - Reverse a linked list Node head2 = reverseList(newList); // Printing reversed linked list Console.Write("Reversed linked list : "); printList(head2); // Step3 - Addition of a original linked list and // its reverse Node addition = addTwoLists(head1, head2); // Step4 - Reverse a addition Linked list Node result = reverseList(addition); // Step5 - Print the resultant linked list Console.Write("Resultant linked list : "); printList(result); } } // This code is contributed by karthik.
JavaScript // JavaScript code of above approach // Define the structure of a // node in the linked list class Node { constructor(x) { this.data = x; this.next = null; } } // Function to return the // reverse of a linked list function reverseList(head) { let prev = null; let cur = head; let next_ = null; while (cur !== null) { next_ = cur.next; cur.next = prev; prev = cur; cur = next_; } return prev; } // Function to return the sum of two // linked lists function addTwoLists(l1, l2) { let dummy = new Node(0); let cur = dummy; let carry = 0; while (l1 !== null || l2 !== null) { let x = l1 ? l1.data : 0; let y = l2 ? l2.data : 0; let summ = carry + x + y; carry = Math.floor(summ / 10); cur.next = new Node(summ % 10); cur = cur.next; if (l1) { l1 = l1.next; } if (l2) { l2 = l2.next; } } if (carry > 0) { cur.next = new Node(carry); } return dummy.next; } // Function to print a linked list function printList(head) { while (head !== null) { console.log(head.data, end=" "); head = head.next; } console.log(); } // Function to create a copy of // a linked list function copyList(head) { let cur = head; let dummy = new Node(0); let copy = dummy; while (cur !== null) { copy.next = new Node(cur.data); copy = copy.next; cur = cur.next; } return dummy.next; } // Driver Code if (typeof require !== 'undefined' && require.main === module) { // Example linked list: // 1 -> 2 -> 3 -> 4 let head1 = new Node(1); head1.next = new Node(2); head1.next.next = new Node(3); head1.next.next.next = new Node(4); // Printing original linked list console.log("Original linked list : "); printList(head1); // Step1 - Make a copy of original // linked list let newList = copyList(head1); // Step2 - Reverse a linked list let head2 = reverseList(newList); // Printing reversed linked list console.log("Reversed linked list : "); printList(head2); // Step3 - Addition of a original // linked list and its reverse let addition = addTwoLists(head1, head2); // Step4 - Reverse a addition // Linked list let result = reverseList(addition); // Step5 - Print the resultant // linked list console.log("Resultant linked list : "); printList(result); } //This code is contributed by shivamsharma215
OutputOriginal linked list : 1 2 3 4 Reversed linked list : 4 3 2 1 Resultant linked list : 5 5 5 5
Time complexity: O(max(m, n)), where m and n are the lengths of the linked lists being added.
Auxiliary Space: O(max(m, n)), as the length of the resultant linked list can be at most one more than the length of the longer linked list. The copyList and reverseList functions have a time complexity of O(n), where n is the length of the linked list.
Similar Reads
Add Two Numbers Represented as Linked List
Given two numbers represented as two lists, the task is to return the sum of two lists. Note: There can be leading zeros in the input lists, but there should not be any leading zeros in the output list. Examples: Input: num1 = 4 -> 5, num2 = 3 -> 4 -> 5Output: 3 -> 9 -> 0 Explanation:
15+ min read
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: Give
9 min read
Add 1 to a number represented as linked list
A number is represented in linked list such that each digit corresponds to a node in linked list. The task is to add 1 to it. Examples: Input: head: 4 -> 5 -> 6Output: head: 4 -> 5 -> 7Explanation: Adding 1 to number represented by Linked List = 456 + 1 = 457 Input: head: 2 -> 1 ->
15+ min read
Add two numbers represented by Linked List without any extra space
Given two numbers represented by two linked lists, write a function that returns sum list. The sum list is linked list representation of addition of two input numbers. Expected Space Complexity O(1). Examples: Input: L1 = 5 -> 6 -> 3 -> NULL L2 = 8 -> 4 -> 2 -> NULL Output: 1 ->
11 min read
Add one to a number represented as linked list | Set 2
Given a singly linked list which represents a number where each node contains only one digit [0 - 9]. The task is to add 1 to the number represented by the given linked list and print the new linked list.Examples: Input: 1 -> 2 -> 9 -> 9 -> NULL Output: Original list is : 1 2 9 9 Resulta
10 min read
Subtract 1 from a number represented as Linked List
Given the head of the linked list representing a positive integer, the task is to print the updated linked list after subtracting 1 from it. Examples: Input: LL = 1 -> 2 -> 3 -> 4Output: 1 -> 2 -> 3 -> 3 Input: LL = 1 -> 2Output: 1 -> 1 Approach: The given problem can be solv
15+ min read
Add Two Numbers represented as Linked List using Recursion
Given two numbers represented as two lists, the task is to return the sum of two lists using recursion. Note: There can be leading zeros in the input lists, but there should not be any leading zeros in the output list. Examples: Input: num1 = 4 -> 5, num2 = 3 -> 4 -> 5Output: 3 -> 9 -
14 min read
Print Doubly Linked list in Reverse Order
Given a doubly-linked list of positive integers. The task is to print the given doubly linked list data in reverse order. Examples: Input: List = 1 <=> 2 <=> 3 <=> 4 <=> 5 Output: 5 4 3 2 1 Input: 10 <=> 20 <=> 30 <=> 40 Output: 40 30 20 10 Approach: Take a
7 min read
Javascript Program For Adding 1 To A Number Represented As Linked List
Number is represented in linked list such that each digit corresponds to a node in linked list. Add 1 to it. For example 1999 is represented as (1-> 9-> 9 -> 9) and adding 1 to it should change it to (2->0->0->0) Below are the steps : Reverse given linked list. For example, 1->
5 min read
An interesting method to print reverse of a linked list
We are given a linked list, we need to print the linked list in reverse order.Examples: Input : list : 5-> 15-> 20-> 25 Output : Reversed Linked list : 25-> 20-> 15-> 5Input : list : 85-> 15-> 4-> 20 Output : Reversed Linked list : 20-> 4-> 15-> 85Input : list : 8
7 min read