Add_TwoNumbers的理解和应用

     花了一个星期理解了这段代码,add_two_numbers

public static void calculateSum(ListNode tresult, ref int carry, int sum)

        {
            if (sum >= 10)
            {
                carry = 1;
                tresult.next = new ListNode(sum - 10);
            }
            else
            {
                carry = 0;
                tresult.next = new ListNode(sum);
            }
        }


        public static ListNode AddTwoNumbers(ListNode l1, ListNode l2)
        {
            ListNode tl1 = l1, tl2 = l2;
            ListNode result = new ListNode(0);
            ListNode tresult = result;
            int carry = 0;


            // both ListNode 1 and ListNode 2 have values
            while (tl1 != null && tl2 != null)
            {
                calculateSum(tresult, ref carry, tl1.val + tl2.val + carry);
                tl1 = tl1.next;
                tl2 = tl2.next;
                tresult = tresult.next;
            }


            // Debug.Assert(!(tl1 != null && tl2 != null), "tl1 and tl2 aren‘t null");
            // either ListNode 1 or ListNode 2 has values (maybe) and don‘t forget carry.
            while (tl1 != null)
            {
                calculateSum(tresult, ref carry, tl1.val + carry);
                tl1 = tl1.next;
                tresult = tresult.next;
            }
            while (tl2 != null)
            {
                calculateSum(tresult, ref carry, tl2.val + carry);
                tl2 = tl2.next;
                tresult = tresult.next;
            }


            // at this time, ListNode 1 and ListNode 2 should be null, however, carry could be null or not
            // Debug.Assert(tl1 == null && tl2 == null, "calculation doesn‘t finish");
            if (carry == 1) tresult.next = new ListNode(1);


            // neither ListNode 1 nor ListNode 2 have values 
            return result.next;
        }
    }
    public class ListNode
    {
        public int val;
        public ListNode next;
        public ListNode(int x) { val = x; }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值