LeetCode题解:Add Two Numbers
2013-11-13 13:50
447 查看
Add Two Numbers
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
思路:
中小学竞赛题。
题解:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode* i1 = l1; ListNode* i2 = l2; ListNode* ret = new ListNode(0); ListNode* ret_last = ret; bool carry = false; while(i1 != nullptr || i2 != nullptr) { int s = 0; if (i1 != nullptr) s = i1->val, i1 = i1->next; if (i2 != nullptr) s += i2->val, i2 = i2->next; s += carry; ret_last->next = new ListNode(s % 10); ret_last = ret_last->next; carry = (s >= 10); } if (carry) ret_last->next = new ListNode(1); ret_last = ret->next; delete ret; return ret_last; } };
相关文章推荐
- ps aux指令詳解
- Error setting expression 'ldstock.ldstocktype.ldstockTypeCode' with value '[Ljava.lang.String;@10f40
- android intent和intent action大全
- jquery1.9以上版本判断浏览器是否为IE6
- iOS App 转移 图文详解
- Ubuntu 12.04 软件管理
- oracle参数文件
- tomcat线程一直处于RUNNABLE,不接受请求
- iftop 监控linux,centos服务器网络流量
- iOS归档
- Linux操作系统下/etc/hosts文件配置方法
- 流形学习概述(转载自CSDN)
- Js中 关于top、clientTop、scrollTop、offsetTop的用法(转载)
- 在c中调用lua函数,获取返回值等
- 通过隐藏option实现select的联动效果 文章源自:烈火网,原文:http://www.veryhuo.com/a/view/10548.html
- java 开发经典网址总结
- 猜字谜游戏
- monkeyrunner 录制回放
- 调试Release发布版程序的Crash错误
- C#链接MySQL