2 Add Two Numbers
2015-09-10 14:43
260 查看
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
My Submissions
/** * 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* resHead = NULL; ListNode* curNode = resHead; int carry = 0; while(l1!=NULL||l2!=NULL||carry>0) { int num1 = 0; if(l1!=NULL) { num1 = l1->val; l1 = l1->next; } int num2 = 0; if(l2!=NULL) { num2 = l2->val; l2 = l2->next; } int sum = num1+num2+carry; ListNode* tempNode = (ListNode*)malloc(sizeof(ListNode)); tempNode->val = sum%10; tempNode->next = NULL; carry = sum/10; if(curNode == NULL) { curNode = tempNode; resHead = curNode; } else { curNode->next = tempNode; curNode = tempNode; } } return resHead; } };
相关文章推荐
- 实现搜索功能
- 磁盘阵列找不着问题
- 第二周实践项目1-C++语言中函数参数传递的三种方式(传值)
- 5分钟弄懂什么是docker
- 批量替换指令
- freemark 笔记
- Android使用命令生成签名密钥文件及使用命令二次签名
- javascript对象
- ATI 驱动教程
- Failed to instantiate the default view controller for UIMainStoryboardFile 'Main' - perhaps the desi
- 在ArcGIS中创建Python工具(三)
- Binary Tree Zigzag Level Order Traversal
- MongoDB—索引操作
- Android activity的回传数据
- C#Lambda表达式
- Boost::split用法详解
- jquery学习(2)--选择器
- weblogic XA驱动的一个报错
- nagios与sendEmail结合实现邮件报警
- PHP下载封装