Question

I have some fundamental doubts in my OO concepts. I am trying to solve this

You have two numbers represented by a linked list, where each node contains a sin- gle digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list. EXAMPLE Input: (3 -> 1 -> 5) + (5 -> 9 -> 2) Output: 8 -> 0 -> 8

I know it can be recursively solved but what I tried was to iteratively test the problem. The method I wrote is this

public LinkedList sum(LinkedList a){
    int carry = 0;
    Node head1 = a.first;
    Node head2 = this.first;
    LinkedList sum = new LinkedList();
    Node k = sum.first;
    if(a.first != null && this.first != null){
        k.item = (head1.item+head2.item) % 10;
        carry = (head1.item+head2.item) / 10;
    }
    head1 = head1.next;
    head2 = head2.next;

    while(head1 != null){
        k.next = new Node((head1.item + head2.item + carry) % 10);
        carry = (head1.item + head2.item) / 10;
        head1 = head1.next;
        head2 = head2.next;
        k = k.next;
    }
    return sum;
}

And the method I am using to call it is this

    LinkedList object1 = new LinkedList();
    LinkedList object2 = new LinkedList();
    object1.insert(5);
    object1.insert(1);
    object1.insert(3);
    object2.insert(2);
    object2.insert(9);
    object2.insert(5);
    LinkedList object3 = object1.sum(object2);
    object3.display();

I am getting a Null Pointer Exception in the line

k.item=(head1.item+head2.item)%10;

How do I modify the sum method to present the correct result. Pleae dont suggest the recursive way as I am already aware of that. The main point of this question is I want to clarify my Object Oriented concepts.

For further info Node class looks like this

class Node {
    public int item;
    public Node next;
    public Node(int val){
        item = val;
    }

    public Node(){}

    public void displayNode() {
        System.out.println("[" + item + "] ");
    }
}

The LinkedList class has one global declaration

private Node first;

Was it helpful?

Solution

Initialising a LinkedList makes an empty LinkedList object, which you then have to populate with Nodes. Your sum LinkedList has no Nodes, so you can't assign Node k to sum.first.

To fix this you need to use Node k = new Node(); However it's best to use/create an add() method in your LinkedList implementation which handles this for you, as well as a remove() method. That way you don't need to simultaneously create and track Nodes in your sum LinkedList.

Apart from that, you should be careful of checking that both head1 and head2 both do not equal null before summing, or you will be restricted to numbers of the same digit-length.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top