Java program to add two numbers represented by linked lists
Clash Royale CLAN TAG#URR8PPP
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;
up vote
2
down vote
favorite
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() 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.
java linked-list
add a comment |Â
up vote
2
down vote
favorite
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() 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.
java linked-list
add a comment |Â
up vote
2
down vote
favorite
up vote
2
down vote
favorite
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() 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.
java linked-list
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() 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.
java linked-list
asked Jan 27 at 14:46
Mayank Gupta
637
637
add a comment |Â
add a comment |Â
1 Answer
1
active
oldest
votes
up vote
2
down vote
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)
@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));
add a comment |Â
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
2
down vote
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)
@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));
add a comment |Â
up vote
2
down vote
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)
@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));
add a comment |Â
up vote
2
down vote
up vote
2
down vote
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)
@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));
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)
@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));
answered Jan 27 at 19:51
coderodde
15.5k533114
15.5k533114
add a comment |Â
add a comment |Â
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f186132%2fjava-program-to-add-two-numbers-represented-by-linked-lists%23new-answer', 'question_page');
);
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password