Last active
August 29, 2015 14:03
-
-
Save st0le/b77c4fb3bfd412ba42fe to your computer and use it in GitHub Desktop.
Add to linked list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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