Created
October 22, 2019 19:49
-
-
Save marta-krzyk-dev/c031589f0d8fd981c855c256e4d1dfbe to your computer and use it in GitHub Desktop.
Add Two Numbers with Linked Lists
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
/** | |
* Definition for singly-linked list. | |
* public class ListNode { | |
* public int val; | |
* public ListNode next; | |
* public ListNode(int x) { val = x; } | |
* } | |
*/ | |
public class Solution { | |
public void PrintNode(ListNode node) | |
{ | |
while (node != null) | |
{ | |
Console.Write(node.val + " -> "); | |
node = node.next; | |
} | |
Console.Write("\n"); | |
} | |
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { | |
if (l1 is null || l2 is null) | |
return null; | |
bool overflow = false; | |
int reminder = 0; | |
ListNode firstNode = null; | |
ListNode result = null; | |
while(l1 != null || l2 != null || overflow) | |
{ | |
int sum = (l1?.val ?? 0) + (l2?.val ?? 0) + (overflow ? 1 : 0); | |
reminder = sum % 10; | |
overflow = sum > 9; | |
if (result is null) | |
firstNode = result = new ListNode(reminder); | |
else | |
{ | |
result.next = new ListNode(reminder); | |
result = result.next; | |
} | |
l1 = l1?.next; | |
l2 = l2?.next; | |
PrintNode(result); | |
} | |
return firstNode; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment