1.题目描述

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

2.我的分析思路

拿到题目,我的第一个思路是这样的:

两个链表,当链表均不为空时,将链表push到栈中,然后同时pop出来,计算栈中数字之和;计算完成后,判断将和对10求余数,放到结果的头结点中,然后把商push到栈中,然后将原始两个链表的值的next赋值为原来的两个链表。

如此递归,即可求出最终值。

不过这里面的判断方式有些问题,比如递归的条件,应该是栈不为空,或者原始的两个链表不为空。

写的代码比较冗余,就不献丑了。

3.其他的思路

现在贴出赞比较多的一个解。

public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode prev = new ListNode(0);
ListNode head = prev;
int carry = 0;
while (l1 != null || l2 != null || carry != 0) {
ListNode cur = new ListNode(0);
int sum = ((l2 == null) ? 0 : l2.val) + ((l1 == null) ? 0 : l1.val) + carry;
cur.val = sum % 10;
carry = sum / 10;
prev.next = cur;
prev = cur;
l1 = (l1 == null) ? l1 : l1.next;
l2 = (l2 == null) ? l2 : l2.next;
}
return head.next;
}

这里没有使用到栈的概念,增加了一个carry,也就是表示商。同时,这里面有个概念,java到底是传值和传引用,这里的head和prev就是这样。

最新文章

  1. Linux使用网盘客户端
  2. FIO使用指南
  3. 重构实践——为了try-catch大兴排场
  4. CodeForces 7C Line
  5. 最近在折腾VPS(持续完善)
  6. .gitignore模板
  7. TextView settextcolor 无效解决方案
  8. javascript 常用api
  9. [最短路]P1828 香甜的黄油 Sweet Butter
  10. Log.isLoggable之一正确的使用姿势
  11. git 仓库原理
  12. oracle 中可以用 case when then else end来处理除数是0的情况
  13. Java远程连接redis, 报错 Connection refused: connect
  14. qt 中的基本知识
  15. iOS中textbox文本框清除圆角
  16. 遍历HashMap的方法(四)
  17. python Django html 模板循环条件
  18. 在css中使用hover来控制其他元素的样式,该两个元素必须是父子元素
  19. sersync+rsync原理及部署
  20. IE8浏览器兼容性问题

热门文章

  1. 初尝2D骨骼动画编辑工具SPINE,并into Unity3D
  2. linux下强行umount卸载设备
  3. solrconfig.xml配置详解
  4. C# 实用小类
  5. WPF自定义滚动条
  6. GO学习笔记 - map
  7. LWIP
  8. scrapy 资料整合
  9. aspx代码审计-2
  10. tomcat 线程模型