Add_TwoNumbers的理解和应用
来源:互联网 发布:大学生心理压力数据 编辑:程序博客网 时间:2024/05/22 13:56
花了一个星期理解了这段代码,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
- Add_TwoNumbers的理解和应用
- VLAN的理解和应用
- 四元数的理解和应用
- 粒度的理解和应用:
- localStorage的理解和应用
- kvc的理解和应用
- Ajax的应用和理解
- 对web.config的理解和应用
- 对web.config的理解和应用
- 对三个流的理解和应用
- PHP中类的理解和应用
- GTD中“项目”的理解和应用
- java、多线程的理解和应用
- 枚举类型的理解和应用
- 枚举类型的理解和应用
- 黑马程序员 多线程的理解和应用
- 枚举类型的理解和应用
- 异或的理解和应用
- opencv图像识别(1-17)
- STM32F10xxx 之 System tick Timer(SYSTICK Timer)(认识2)
- spring AspectJ的Execution表达式-备忘笔记(转)
- 595. Big Countries
- DVD租借系统java小项目编程
- Add_TwoNumbers的理解和应用
- 神经网络
- ThreadLocal原理与应用详解(1)
- avformat_find_stream_info分析
- unity 进度条制作:Slider,Scrollbar
- 第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数
- android版本更新适配7.0,解决7.0手机无法更新安装apk
- opencv图像识别(18-37)
- 维护电脑速度