I recently got a programming question.
There are 2 linked lists. Each node stores a value from 1 to 9 (indicating one index number). Hence 123 would be a linked list 1-> 2-> 3
The task was to create a function:
static LinkedListNode getSum(LinkedListNode a, LinkedListNode b)
which will return the sum of the values ββin 2 related list arguments.
If array a: 1-> 2-> 3-> 4
And array b: 5-> 6-> 7-> 8
The answer should be: 6-> 9-> 1-> 2
Here is my algorithm:
Go through each node in a and b, get the values ββas an integer and add them. Create a new linked list with these values.
Here is the code: it works with O (n) complexity, as I assume. Once through each of the inputs of the array and once to create an output array.
Any improvements? Improved algorithms ... or code improvements
public class LinkedListNode { LinkedListNode next; int value; public LinkedListNode(int value) { this.value = value; this.next = null; } static int getValue(LinkedListNode node) { int value = node.value; while (node.next != null) { node = node.next; value = value * 10 + node.value; } return value; } static LinkedListNode getSum(LinkedListNode a, LinkedListNode b) { LinkedListNode answer = new LinkedListNode(0); LinkedListNode ans = answer; int aval = getValue(a); int bval = getValue(b); int result = aval + bval; while (result > 0) { int len = (int) Math.pow((double) 10, (double) String.valueOf(result).length() - 1); int val = result / len; ans.next = new LinkedListNode(val); ans = ans.next; result = result - val*len; } return answer.next; } }
source share