Skip to content

Instantly share code, notes, and snippets.

@chatay
Last active February 12, 2023 14:58
Show Gist options
  • Save chatay/3a5e2306276e5f6098665adb0d2f059b to your computer and use it in GitHub Desktop.
Save chatay/3a5e2306276e5f6098665adb0d2f059b to your computer and use it in GitHub Desktop.
AddTwoNumbers leetcode
public class ListNodeSolution
{
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int val = 0, ListNode next = null)
{
this.val = val;
this.next = next;
}
}
public ListNode SumTwoValues(ListNode list1, ListNode list2)
{
ListNode currentNode = null;
ListNode head = null;
int carry = 0;
while (list1 != null || list2 != null)
{
int sum = GetSum(list1) + GetSum(list2) + carry;
carry = sum / 10;
int value = sum % 10;
ListNode node = new ListNode(value);
currentNode ??= head = node;
currentNode.next = node;
currentNode = currentNode.next;
list1 = list1?.next;
list2 = list2?.next;
}
return head;
}
public int GetSum(ListNode node)
{
return node?.val ?? 0;
}
static void Main(string[] args)
{
ListNodeSolution listNode = new ListNodeSolution();
ListNode head1 = new ListNode();
int[] numbers = new[] { 47, 56, 127, 963, 47, 15, 98, 32, 1 };
//head1.FindIndexRecursiveHelper(numbers, 1111, 8);
//head1.FindIndex_Recursive(numbers, 1, 8);
head1 = new ListNode(9);
head1.next = new ListNode(9);
head1.next.next = new ListNode(9);
head1.next.next.next = new ListNode(9);
head1.next.next.next.next = new ListNode(9);
head1.next.next.next.next.next = new ListNode(9);
head1.next.next.next.next.next.next = new ListNode(9);
Console.Write("First list is ");
ListNode head2 = new ListNode();
head2 = new ListNode(9);
head2.next = new ListNode(9);
head2.next.next = new ListNode(9);
head2.next.next.next = new ListNode(9);
Console.Write("Second list is ");
listNode.SumTwoValues(head1, head2);
Console.ReadLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment