Instantly share code, notes, and snippets.

Embed
What would you like to do?
Leetcode 2: Add two numbers - prototype - add two linked lists with only one node
/// <summary>
/// add two linked list together, both have only one node.
/// </summary>
/// <param name="l1"></param>
/// <param name="l2"></param>
/// <returns></returns>
public ListNode AddTwoNumbers_prototype(ListNode l1, ListNode l2)
{
if (l1 == null || l2 == null)
{
return l1 == null ? l2 : l1;
}
int value = l1.val + l2.val;
var result = new ListNode(value % 10);
if (value >= 10)
{
// make this carry as a linked list as well
result.next = AddTwoNumbers_prototype(new ListNode(value / 10), null);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment