c#链表

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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值