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

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

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807

class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
int x = 0;
ListNode* head = NULL;
ListNode* last = NULL;
while(l1 && l2)
{
int temp = l1 ->val + l2 ->val + x;
x = temp / 10;
temp = temp % 10;
if(head == NULL)
{
head = new ListNode(temp);
last = head;
}
else
{
last ->next = new ListNode(temp);
last = last ->next;
}
l1 = l1 ->next;
l2 = l2 ->next;
}
while(l1)
{
int temp = l1 ->val + x;
x = temp / 10;
temp = temp % 10;
if(head == NULL)
{
head = new ListNode(temp);
last = head;
}
else
{
last ->next = new ListNode(temp);
last = last ->next;
}
l1 = l1 ->next;
}
while(l2)
{
int temp = l2 ->val + x;
x = temp / 10;
temp = temp % 10;
if(head == NULL)
{
head = new ListNode(temp);
last = head;
}
else
{
last ->next = new ListNode(temp);
last = last ->next;
}
l2 = l2 ->next;
}
if(x != 0)
{
last ->next = new ListNode(x);
last = last ->next;
}
return head;
}
};

最新文章

  1. T-SQL 实现行转列
  2. 在.NET中使用管道将输出流转换为输入流
  3. MySQL中索引和优化的用法总结
  4. 网页游戏外挂辅助AMF模拟通讯必备
  5. springmvc之前后台传值
  6. 灭顶之灾之网络电视精灵——S2 2.8
  7. Genymotion模拟器环境搭建中的各种坑,终极解决办法
  8. watchdog机制
  9. maven工程代码关联源代码配置
  10. Builder模式在Java中的应用(转)
  11. listview使用总结
  12. C# 实体model验证输出
  13. C++中Map常见用法以及按照value排序
  14. 第一篇 Flask
  15. laravel前后台路由分离
  16. (转)c#中const与readonly区别
  17. Apache Rewrite规则详解[转]
  18. Hystrix已经停止开发,官方推荐替代项目Resilience4j
  19. assetBundle打包脚本与LUA
  20. Xampp mysql启动

热门文章

  1. 深度学习(二十六)Network In Network学习笔记
  2. SQL Server日常积累
  3. deepfake安装python常用命令
  4. day43作业
  5. Vue 本地代理 纯前端技术解决跨域
  6. 创建一个欢迎 cookie 利用用户在提示框中输入的数据创建一个 JavaScript Cookie,当该用户再次访问该页面时,根据 cookie 中的信息发出欢迎信息。
  7. 禁止input文本框输入select无法选择
  8. Java数据结构和算法(六)--二叉树
  9. CF 500B New Year Permutation
  10. Ubuntu中安装gdal python版本