Friday, April 3, 2015

Java code that adds '1' to linked list of digits by reversing the list.


The idea is to reverse the list first. Keep adding the carry from the start to the end and perhaps, create a carry node at the end and then reverse back to normal order.

========================================================================

class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// create LL
                 ..
                 ..          
                 ..
                 ..
Node reversedHead = reverseLL(head);
incrementLL(reversedHead);
Node normal = reverseLL(reversedHead);
}

public static void incrementLL(Node head)
{
Node current = head;
Node previous = current;
int carry = 1;

while( current != null && carry > 0 )
{
int temp = current.value;

temp += carry;
carry = temp / 10;
temp %= 10;

current.value = temp;
previous = current;
current = current.next;
}

if( carry > 0 )
{
Node last = createNewNode(carry);
previous.next = last;
}

}

public static Node reverseLL(Node head)
{
Node current = head;
Node previous = null;

while( current != null )
{
Node temp = current.next;

current.next = previous;
previous = current;
current = temp;
}

return previous;
}

}
========================================================================

Test Execute it here.

No comments:

Post a Comment