using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
var l1 = Test.generateList(new int[] { 1, 5, 7 });
var l2 = Test.generateList(new int[] { 9, 8, 2});
Test.printList(l1);
Test.printList(l2);
var sum = AddListNode(l1, l2);
Test.printList(sum);
Console.ReadKey();
}
private static ListNode AddListNode(ListNode node1,ListNode node2)
{
ListNode reslutNode = new ListNode(-1);
ListNode tmpNode = reslutNode;
int tmpval = 0;
do
{
int resultNum = (node1.val + node2.val)>=10? (node1.val + node2.val)-10+tmpval: (node1.val + node2.val)+ tmpval;
tmpval = (node1.val + node2.val) >=10 ? 1 : 0;
tmpNode.next = new ListNode(resultNum);
node1 = node1.next;
node2 = node2.next;
tmpNode = tmpNode.next;
} while (node1 != null && node2!= null);
return reslutNode.next;
}
}
public static class Test
{
public static ListNode generateList(int[] vals)
{
ListNode res = null;
ListNode last = null;
foreach (var val in vals)
{
if (res is null)
{
res = new ListNode(val);
last = res;
}
else
{
last.next = new ListNode(val);
last = last.next;
}
}
return res;
}
public static void printList(ListNode l)
{
while (l != null)
{
Console.Write($"{l.val}, ");
l = l.next;
}
Console.WriteLine("");
}
}
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x) { val = x; }
}
}
leetcode第二题:
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。