题目标签:Linked List

  题目给了我们两个 数字的linked list,让我们把它们相加,返回一个新的linked list。

  因为题目要求不能 reverse,可以把 两个list 的数字都 存入 两个stack。利用了stack的特性,就可以从后面把数字相加,具体看code。

Java Solution:

Runtime:  6 ms, faster than 51.06%

Memory Usage: 45.4 MB, less than 64.71%

完成日期:07/08/2019

关键点:stack

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>(); // store two numbers into stacks
while(l1 != null) {
s1.push(l1.val);
l1 = l1.next;
} while(l2 != null) {
s2.push(l2.val);
l2 = l2.next;
} // adding two numbers from stacks
int sum = 0;
ListNode list = new ListNode(0); while(!s1.empty() || !s2.empty()) {
if(!s1.empty())
sum += s1.pop();
if(!s2.empty())
sum += s2.pop(); list.val = sum % 10; // get the value
ListNode head = new ListNode(sum / 10); // get the carry
head.next = list;
list = head; sum /= 10;
} // need to check if the head is 0 or not
return list.val == 0 ? list.next : list;
}
}

参考资料:LeetCode Discuss

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

最新文章

  1. 微信小程序,我的英雄列表
  2. JSP中的Servlet及Filter
  3. ExceptionLess新玩法 -- 审计日志
  4. Hibernate原生SQL查询多表关联,SQL语句要注意的问题
  5. Android开源项目汇总【转】
  6. 读取jar内的配置文件
  7. JAVA 文件下载乱码问题解决办法
  8. java虚拟机涉及内存溢出
  9. Java基础知识强化62:Arrays工具类之概述和使用
  10. Android 使用monkey自动测试
  11. Spring摘记
  12. Hibernate 配置详解(11)
  13. Win10使用中的一些问题
  14. UVa/数组和字符串习题集
  15. jQuer __Ajax DOM
  16. Centos 安装lnmp完整版
  17. MyBatis基础入门《七》查询参数传入对象
  18. asp.net利用HttpModule实现防sql注入和加载样式和JS文件
  19. jedispool资源释放
  20. arcgis英文版补丁下载地址

热门文章

  1. Magento开启模板路径提示
  2. 牛客 某练习赛 Data Structure
  3. cf期望概率专题
  4. Github上发布托管和下载
  5. 奇技淫巧之Delphi和JavaScript互通
  6. NX二次开发-Block UI C++界面Face Collector(面收集器)控件的获取(持续补充 )
  7. TESTNG听录音笔记
  8. JS闭包的详解
  9. B606 ChangeNet
  10. PHP面试 PHP基础知识 八(会话控制)