Skip to content

Instantly share code, notes, and snippets.

@st0le
Last active August 29, 2015 14:03
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 st0le/b77c4fb3bfd412ba42fe to your computer and use it in GitHub Desktop.
Save st0le/b77c4fb3bfd412ba42fe to your computer and use it in GitHub Desktop.
Add to linked list
private Node Add(Node a, Node b)
{
Node c = null, answer = null;
int carry = 0;
while (a != null && b != null)
{
carry += a.digit + b.digit;
if (c == null)
answer = c = new Node(carry % 10, null);
else
c = c.next = new Node(carry % 10, null);
carry /= 10;
a = a.next;
b = b.next;
}
Node i = (a != null) ? a : b; // bigger number is still left
while (i != null)
{
carry += i.digit;
if (c == null)
answer = c = new Node(carry % 10, null);
else
c = c.next = new Node(carry % 10, null);
carry /= 10;
i = i.next;
}
while (carry > 0) //left over carry
{
c = c.next = new Node(carry % 10, null);
carry /= 10;
}
return answer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment