一、给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807 -----------------------------------------------------------
1、定义一个链表

class LinkedListNode
{
  public object Value;
  public LinkedListNode Next;

  public LinkedListNode()
  {
    this.Value = null;
    this.Next = null;
  }

  public LinkedListNode(int value)
  {
    this.Value = value;
    this.Next = null;
  }
}

public static LinkedListNode AddTwoNumber(LinkedListNode n1, LinkedListNode n2)
{
  LinkedListNode ret = new LinkedListNode();
  LinkedListNode cur = ret;
  int carry = 0;
  int sum;

  while (n1 != null || n2 != null)
  {
    sum = (n1 == null ? 0 : (int)n1.Value) + (n2 == null ? 0 : (int)n2.Value) + carry;
    carry = sum / 10;
    cur.Value = sum % 10;

    if (n1 != null)
      n1 = n1.Next;
    if (n2 != null)
      n2 = n2.Next;

    cur.Next = new LinkedListNode();
    cur = cur.Next;
  }

  if (carry == 1)
    cur.Next = new LinkedListNode(1);

  return ret;
}

调用

LinkedListNode n1 = new LinkedListNode(2);
n1.Next = new LinkedListNode(4);
n1.Next.Next= new LinkedListNode(3);

LinkedListNode n2 = new LinkedListNode(5);
n2.Next = new LinkedListNode(6);
n2.Next.Next = new LinkedListNode(8);

LinkedListNode nk = AddTwoNumber(n1, n2);

最新文章

  1. 2014优秀的好用的20款免费jQuery插件推荐
  2. java内存配置
  3. JAVA自定义事件监听完整例子---sunfruit[转]
  4. OPW-00001: Unable to open password-file
  5. 《Python 学习手册4th》 第四章 介绍Python对象类型
  6. leetcode first bad version python
  7. poj 1041 John's trip 欧拉回路
  8. jquery下php与ajax的互传数据(json格式)自我总结
  9. vr & obv
  10. String的valueOf()用于将其它类型转换为字符串
  11. C# 利用位运算传递多个参数方法
  12. 常见Python脚本
  13. 【C++】如何接收函数return返回来的数组元素
  14. 2.ES6引进的新特性——类Class
  15. React 中的 Component、PureComponent、无状态组件 之间的比较
  16. vs2013 std::sort 分析
  17. River Hopscotch
  18. Mac OSX安装 GitLab 5.x
  19. UVA-10054 The Necklace (欧拉回路)
  20. C# 高德地图调用帮助类 GaodeHelper

热门文章

  1. iOS gzip解压
  2. HDU 1022 Train Problem I 模拟栈题解
  3. Effective C++ 条款12
  4. directshow 获取本地摄像头播放
  5. 用fcntl锁一个文件来保护操作
  6. POJ 1144 Network【割顶】
  7. 3、Go Exit
  8. 如何知道 CPU 是否支持虚拟化技术(VT)
  9. JavaScript:理解事件循环
  10. 学习优化《机器学习与优化》中文PDF+英文PDF