Add two numbers represented by Linked List in java

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.

Java Linked List Interview Programs:

 

Given two number represent by linked list, calculate sum of the numbers and store result in new linked list. Each node of linked list is represented by single digit and head node is most significant digit.
For example:
Sum of two number:
56712
+   6359
———–
63071

So it will be represented in below format as linked list:

Algorithm:

  • Create two linkedlist which will represent above two numbers.
  • Reverse both linked list.
  • Add two node values (Each node is being represented as single digit)  starting from heads of two linkedlist.
  • If sum is of above two node values is more than 10, then forward the carry.
  • Follow basic mathematical rules for addition.
Below image will make it clear:
  • Reverse the result , so that we will get actual sum of numbers.

Java program:

package org.arpit.java2blog;

public class AddTwoNumberLinkedList{
    /*
     * @Author: Arpit Mandliya
     * */
    private static Node head;

    private static class Node {
        private int value;
        private Node next;

        Node(int value) {
            this.value = value;

        }
    }

    public void addToTheLast(Node node) {

        if (head == null) {
            head = node;
        } else {
            Node temp = head;
            while (temp.next != null)
                temp = temp.next;

            temp.next = node;
        }
    }

    public void printList(Node printNode) {
        Node temp = printNode;
        while (temp != null) {
            System.out.format("%d ", temp.value);
            temp = temp.next;
        }
        System.out.println();
    }

    public static Node reverseLinkedList(Node node) {
        if (node == null || node.next == null) {
            return node;
        }

        Node remaining = reverseLinkedList(node.next);
        node.next.next = node;
        node.next = null;
        return remaining;
    }

    // This function will do sum of numbers represented by linked list
    public Node findSumOfNumbers(Node l1, Node l2) {
        int carry =0;

        Node newHead = null;
        Node tempNodeForIteration=null;
        int sum=0;

        int firstIter=0;
        while(l1!=null || l2!=null)
        {
            firstIter++;
            sum=carry;
            if(l1!=null)
            {
                sum=sum+l1.value;
                l1=l1.next;
            }

            if(l2!=null)
            {
                sum=sum+l2.value;
                l2=l2.next;
            }

            carry=sum/10;
            sum=sum%10;
            // Check if it first node for the result
            if(firstIter==1)
            {
                tempNodeForIteration = new Node(sum);
                newHead=tempNodeForIteration;
            }
            else
            {
                Node tempSumNode=new Node(sum);
                tempNodeForIteration.next=tempSumNode;
                tempNodeForIteration=tempNodeForIteration.next;
            }

        }
        if(carry!=0)
        {
            Node tempNode=new Node(carry);
            tempNodeForIteration.next=tempNode;
        }
        return newHead;
    }

    public static void main(String[] args) {
        AddTwoNumberLinkedList list = new AddTwoNumberLinkedList();
        // Creating a linked list
        Node head1=new Node(5);
        list.addToTheLast(head1);
        list.addToTheLast(new Node(6));
        list.addToTheLast(new Node(7));
        list.addToTheLast(new Node(1));
        list.addToTheLast(new Node(2));
        System.out.print("Number 1:  ");
        list.printList(head1);
        head=null;
        Node head2=new Node(6);
        list.addToTheLast(head2);
        list.addToTheLast(new Node(3));
        list.addToTheLast(new Node(5));
        list.addToTheLast(new Node(9));

        System.out.print("Number 2:  ");
        list.printList(head2);
        // Reversing first linkedList
        head1=reverseLinkedList(head1);

        //Reversing second linkedList
        head2=reverseLinkedList(head2);

        // function to find sum of two linkedlist represent by number
        Node result= list.findSumOfNumbers(head1,head2);
        // Reverse the above linkedlist to get actual sum
        result=reverseLinkedList(result);
        System.out.print("Sum:  ");
        list.printList(result);
    }
}

When you run above program , you will get following output:

Number 1: 5 6 7 1 2
Number 2: 6 3 5 9
Sum: 6 3 0 7 1

Please go through Frequently asked Interview programs in java  for more such programs
.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.