Skip to content

Instantly share code, notes, and snippets.

@marta-krzyk-dev
Created October 22, 2019 19:49
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 marta-krzyk-dev/c031589f0d8fd981c855c256e4d1dfbe to your computer and use it in GitHub Desktop.
Save marta-krzyk-dev/c031589f0d8fd981c855c256e4d1dfbe to your computer and use it in GitHub Desktop.
Add Two Numbers with Linked Lists
/**
* 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