2
\$\begingroup\$

First of all, I found this question on Leetcode.The two digits of the two numbers are stored in reverse order.We have to add them and create a single linked list composed of the sum of the two numbers.Here is the question for reference.

public class LLAdd {
    static Node head, head1, head2;

    static class Node {
        Node link;
        int data;

        Node(int data){
            this.data = data;
            this.link = null;
        }
    }

public static void printList(Node head){
    Node curr = head;
    while(curr!=null){
        System.out.print(curr.data + "->");
        curr = curr.link;
    }
    System.out.print("NULL \n");
}

public static Node push(int data, Node head){
    Node new_node = new Node(data);
    new_node.link = head;
    head = new_node;
    return head;
}

public static Node addNumbers(){
    Node curr1 = head1, curr2 = head2;

    if(curr1==null) {
        return curr2;
    }
    if(curr2==null) {
        return curr1;
    }

    int data = 0, units = 0, tens = 0;

    while(curr1!=null || curr2!=null){
        data = (curr1!=null ? curr1.data : 0) + (curr2!=null ? curr2.data : 0) + tens;
        units = data % 10;
        tens = data / 10;
        head = push(units, head);
        curr1 = curr1!=null ? curr1.link : null;
        curr2 = curr2!=null ? curr2.link : null;
        if(curr1==null && curr2==null && tens > 0){
            head = push(tens, head);
        }
    }   
    return head;
}

public static void main(String[] args){

    head1 = push(3, head1);
    head1 = push(4, head1);
    head1 = push(2, head1);

    head2 = push(4, head2);
    head2 = push(6, head2);
    head2 = push(5, head2);

    System.out.println("Lists before addition: ");
    printList(head1);
    printList(head2);

    System.out.println("List after addition : ");
    head = addNumbers();
    printList(head);
   }
}   

Please review this code and suggest better ways to solve this problem.Thank you.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Advice 1

Fix your code indentation. Instead of

public class LLAdd {
...
public static void printList(Node head){
...
}
...
}

you should have

public class LLAd {
    ...
    public static void printList(Node head){
        ...
    }
    ...
}

Advice 2

In method definitions, one, according to common Java coding conventions, must have a single space between parameter-closing ) and a block-opening {. Instead of

public static void printList(Node head){
    ...
}

you should write

public static void printList(Node head) {
    ...                                ^-- Space!
}

Advice 3

The class name LLAdd is really poor. Taking a look of what it does, you could come up with the name, say, BigInteger.

Advice 4

static Node head, head1, head2;

This is an anti-pattern since there is only one "instance" of the class. Make these non-static and private instead.

Advice 5

Node new_node ...

Once again, Java coding conventions dictate that the fields/variables are named in CamelCase:

Node newNode ...

Advice 6

static class Node {
    Node link;
    int data;

    Node(int data){
        this.data = data;
        this.link = null;
    }
}

Make this private and final since most likely you don't want to shine into the entire package, and you hardly need to derive from that class. Also, I would rename link to next. Finally for this advice, you don't need this.link = null;. Java sets all the object fields to null by default.

Advice 7 In principle, I think you should make your BigInteger/LLAdd immutable.

Advice 8

public static Node push(int data, Node head)...

That's is a poor name too. Looking from what it does, I suggest you rename it to prependDigit. Also, I believe you would want to check that data is within the range 0-9 unless you want to allow dealing with arbitrary radices.

Advice 9

Instead of implementing printList, I would override toString.

Alternative implementation

import java.util.Scanner;

public final class BigInteger {

    private static final class Digit {
        Digit next;
        int digit;

        Digit(char ch) {
            this.digit = ch - '0';
        }

        Digit(int digit) {
            this.digit = digit;
        }
    }

    private Digit leastSignificantDigit;

    public BigInteger(String integerText) {
        checkCharacters(integerText);
        leastSignificantDigit = 
                new Digit(integerText.charAt(integerText.length() - 1));
        Digit head = leastSignificantDigit;

        for (int i = integerText.length() - 2; i >= 0; i--) {
            Digit digit = new Digit(integerText.charAt(i));
            head.next = digit;
            head = digit;
        }
    }

    private BigInteger() {

    }

    public BigInteger add(BigInteger other) {
        Digit digit1 = leastSignificantDigit;
        Digit digit2 = other.leastSignificantDigit;
        BigInteger result = new BigInteger();
        Digit headDigit = null;
        boolean carry = false;

        while (digit1 != null || digit2 != null) {
            int intDigit1 = digit1 == null ? 0 : digit1.digit;
            int intDigit2 = digit2 == null ? 0 : digit2.digit;
            int sum = intDigit1 + intDigit2 + (carry ? 1 : 0);
            carry = sum > 9;
            int currentDigit = carry ? (sum - 10) : sum;
            Digit digit = new Digit(currentDigit);

            if (result.leastSignificantDigit == null) {
                result.leastSignificantDigit = digit;
                headDigit = digit;
            } else {
                headDigit.next = digit;
                headDigit = digit;
            }

            if (digit1 != null) {
                digit1 = digit1.next;
            }

            if (digit2 != null) {
                digit2 = digit2.next; 
            }
        }

        if (carry) {
            headDigit.next = new Digit(1);
        }

        return result;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();

        for (Digit digit = leastSignificantDigit; 
                digit != null; 
                digit = digit.next) {
            stringBuilder.append((char)('0' + digit.digit));
        }

        return stringBuilder.reverse().toString();
    }

    private void checkCharacters(String integerText) {
        for (char ch : integerText.toCharArray()) {
            if (!Character.isDigit(ch)) {
                throw new IllegalArgumentException(
                        "Character '" + ch + "' is not a valid digit.");
            }
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        BigInteger bi1 = new BigInteger(scanner.nextLine());
        BigInteger bi2 = new BigInteger(scanner.nextLine());
        System.out.println(bi1 + " + " + bi2 + " = " + bi1.add(bi2));
    }
}
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.