Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@chouclee
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chouclee/97d1aa3bf0461fa82642 to your computer and use it in GitHub Desktop.
Save chouclee/97d1aa3bf0461fa82642 to your computer and use it in GitHub Desktop.
[CC150][2.5] You have two numbers represented by a linked list, where each node contains a single 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
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Random;
public class add {
public static LinkedList<Integer> addList(LinkedList<Integer> a,
LinkedList<Integer> b) {
LinkedList<Integer> result = new LinkedList<Integer>();
ListIterator<Integer> iterA = a.listIterator();
ListIterator<Integer> iterB = b.listIterator();
int m = 0;
int addValue;
while (iterA.hasNext() || iterB.hasNext()) {
addValue = (iterA.hasNext() ? iterA.next() : 0) +
(iterB.hasNext() ? iterB.next() : 0) + m;
result.add(addValue % 10); //add signal digit to result
m = (addValue - addValue % 10) / 10; // update tens digit for next loop
}
return result;
}
public static void main (String[] args) {
Random rd = new Random();
LinkedList<Integer> testA = new LinkedList<Integer>();
LinkedList<Integer> testB = new LinkedList<Integer>();
System.out.println("*************test***************");
for (int i = 0; i < 5; i++)
testA.add(rd.nextInt(10));
System.out.println(testA.toString());
for (int i = 0; i < 7; i++)
testB.add(rd.nextInt(10));
System.out.println(testB.toString());
LinkedList<Integer> result = add.addList(testA, testB);
System.out.println(result.toString()+"\n");
System.out.println("*************test***************");
testA.clear();
testB.clear();
result.clear();
for (int i = 0; i < 8; i++)
testA.add(rd.nextInt(10));
System.out.println(testA.toString());
for (int i = 0; i < 5; i++)
testB.add(rd.nextInt(10));
System.out.println(testB.toString());
result = add.addList(testA, testB);
System.out.println(result.toString()+"\n");
System.out.println("*************test***************");
testA.clear();
testB.clear();
result.clear();
for (int i = 0; i < 5; i++)
testA.add(rd.nextInt(10));
System.out.println(testA.toString());
System.out.println(testB.toString());
result = add.addList(testA, testB);
System.out.println(result.toString()+"\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment