Created
July 11, 2018 22:24
-
-
Save jianminchen/13359f8d654e683bb2200849e5447e7d to your computer and use it in GitHub Desktop.
Leetcode 2: Add two numbers - prototype - add two linked lists with only one node
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
/// <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