题干:

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

注:

题目中链表的定义为

 public class ListNode {
int val;
ListNode next; ListNode(int val) {
this.val = val;
}
}

分析:

  题干中链表中的数是倒序存储的,题干中给的例子其实是:342+465=807。

  我们定义一个节点dummyHead来指向结果的头结点,然后定义三个节点p,q,curr分别用来记录l1当前节点,l2当前节点,结果当前节点。

  定义int carry来记录是否有进位。

public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null)
p = p.next;
if (q != null)
q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
return dummyHead.next;
}

最新文章

  1. 创建agsXMPP 自定义packet types
  2. c = (a / b, a%b) 运算输出顺序
  3. 让Entity Framework启动不再效验__MigrationHistory表
  4. jQuery 根据城市时区,选择对应的即时时间
  5. 解压和生成 system.img&data.img ( ext4格式)
  6. MYSQL delete 从多人表中删除
  7. tiny4412学习笔记-将uboot、zImage、文件系统烧到emmc中
  8. Android破解心得——记学习七少月安卓大型安全公开课
  9. react 或 vue 中引用 jQuery 插件
  10. Windows获取进程完整路径
  11. docker+springboot+elasticsearch+kibana+elasticsearch-head整合(详细说明 ,看这一篇就够了)
  12. r里面如何实现两列数据合并为一列
  13. Flask 中的 CBV 与上传文件
  14. bzoj1477: 青蛙的约会(exgcd)
  15. 天天爱跑步&&弹球
  16. ubuntu12.04下Qt调试器的使用
  17. HTIML5 真的打败了Flash?新测试结果出人意料
  18. ERROR - Undefined placeholders found in template:
  19. [转]C结构体之位域(位段)
  20. BFS搜索:POJ No 3669 Meteor Shower

热门文章

  1. 三十道DP练习(持续更新)(pw:DP)
  2. freebsd网卡驱动程序详解
  3. [ARC068F] Solitaire [DP]
  4. ubuntu安装出现"删除initramfs-tools时出错",subprocess installed post-installation script returned error exit status 1
  5. Codeforces 932.A Palindromic Supersequence
  6. SpringMVC+MyBatis+Shiro 配置文件详解
  7. MyBatis的常见错误总结
  8. ACdream 1210 Chinese Girls' Amusement(高精度)
  9. Scenes in Cocos2D
  10. Golang/Go语言/Go IDE/Go windows环境搭建/Go自动提示编译器/GoSublime