题目说明:

You are given two linked lists representing two non-negative numbers. 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.

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

程序代码:

#include <gtest/gtest.h>

using namespace std;

struct ListNode {

    int val;
ListNode *next;
ListNode(int x) :
val(x), next(NULL)
{}
}; ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
ListNode* result = 0;
ListNode* current = 0;
int carry = 0; while (l1 != NULL || l2 != NULL)
{
int value = 0;
if (l1 != NULL)
{
value += l1->val;
l1 = l1->next;
} if (l2 != NULL)
{
value += l2->val;
l2 = l2->next;
} if (current == NULL)
{
current = result = new ListNode(value % 10);
carry = value / 10;
}
else
{
current->next = new ListNode((value + carry) % 10);
carry = (value + carry) / 10;
current = current->next;
}
} if (carry)
{
if (current == NULL)
{
current = result = new ListNode(carry);
}
else
{
current->next = new ListNode(carry);
current = current->next;
}
} return result;
} TEST(Pratices, tAddTwoNumbers)
{
// (2 -> 4 -> 3) + (5 -> 6 -> 4) 7 -> 0 -> 8
ListNode* l1 = new ListNode(2);
l1->next = new ListNode(4);
l1->next->next = new ListNode(3); ListNode* l2 = new ListNode(5);
l2->next = new ListNode(6);
l2->next->next = new ListNode(4); ListNode* result = addTwoNumbers(l1,l2); // NULL + (2 -> 4 -> 3)
result = addTwoNumbers(NULL,l1); // (2 -> 4 -> 3) + (5 -> 6 -> 4 -> 4)
l2->next->next->next = new ListNode(4);
result = addTwoNumbers(l1,l2); // 1 + 9->9
l1 = new ListNode(1);
l2 = new ListNode(9);
l2->next = new ListNode(9); result = addTwoNumbers(l1,l2);
}

最新文章

  1. unity 3d 解析 json
  2. 黄聪:phpexcel中文教程-设置表格字体颜色背景样式、数据格式、对齐方式、添加图片、批注、文字块、合并拆分单元格、单元格密码保护
  3. String根据、拆分
  4. ASP.NET MVC案例——————拦截器
  5. webapi支持跨域访问
  6. c#中的math类
  7. shell读取文件每行,并执行命令
  8. html frames
  9. (四)、 nodejs中Async详解之一:流程控制
  10. lintcode :Partition List 链表划分
  11. Android网络编程之Http通信
  12. NOSQL EYE开源
  13. html中的块元素和内联元素的区别
  14. 魔改版ss-panel v3前端配置文件
  15. 美链BEC合约漏洞技术分析
  16. nginx的proxy_pass路径转发规则最后带/问题
  17. datetime的小坑
  18. 在计算机通信中,可靠交付应当由谁来负责?是网络还是端系统? 网络层协议 MAC帧、IP数据报、TCP报文 关系 IP地址与硬件地址 链路层与网络层
  19. Log4Net使用指南之用log4net记录日志到数据库(含有自定义属性)------附Demo例子源代码
  20. c# 控制台定时程序

热门文章

  1. 网络基础 02_TCP/IP模型
  2. Service Discovery protocol(SDP)
  3. [转] Scala Async 库 (Scala future, await, async)
  4. linux安装oracle 报错[INS-20802] Oracle Net Configuration Assistant failed 解决办法
  5. windows系统PHP7开启curl_init
  6. iconfont的引入方法
  7. DesUtils工具类
  8. C#自定义处理事件(作者还没完全理解事件和委托,所以有可能错漏百出)
  9. select2和bootstrap模态框一起使用导致select2的input获取不到焦点问题
  10. [译]用R语言做挖掘数据《六》