2. Add Two Numbers
2016-06-13 22:04
309 查看
1. 问题描述
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
Tags: Linked List Math
Similar Problems: (M) Multiply Strings (E) Add Binary
2. 解答思路
3. 代码
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ #include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { if (NULL == l1) { return l2; } if (NULL == l2) { return l1; } return addTwoNum(l1, l2); } public: void PrintList(ListNode* l1) { if (NULL == l1) { return; } ListNode *pt = l1; while (NULL != pt) { std::cout<< pt->val << " "; pt = pt->next; } } private: ListNode* addTwoNum(ListNode* ptLar, ListNode* ptSma) { ListNode *pLar = ptLar; ListNode *pSma = ptSma; int t = 0; while (NULL != pSma && NULL != pLar) { int sum = pLar->val + pSma->val + t; pLar->val = sum%10; pSma->val = pLar->val; t = sum/10; if ((NULL != pSma->next && NULL != pLar->next)) { pSma = pSma->next; pLar = pLar->next; } else { break; } } if (0 == t) { if (NULL == pSma->next) { return ptLar; } else { return ptSma; } } if (NULL == pSma->next && NULL == pLar->next) { ListNode *pNew = new ListNode(1); pLar->next = pNew; return ptLar; } if ( NULL != pLar->next) { addone(pLar); return ptLar; } else { addone(pSma); return ptSma; } } void addone(ListNode *pLar, int t = 1) { pLar = pLar->next; while (NULL != pLar) { int sum = pLar->val + t; pLar->val = sum%10; t = sum/10; if (0 == t) { break; } else { if (NULL == pLar->next) { ListNode *pNew = new ListNode(1); pLar->next = pNew; break; } else { pLar = pLar->next; } } } } };
4. 反思
相关文章推荐
- 闲话数据库(一)第一范式/第二范式
- codeforces 656b Scrambled
- HTML5 MathMl
- 黑苹果安装参考
- 来点不一样的:前端手指操
- ant常用task之condition
- Supervisor的安装与使用入门
- HDU 1241 Oil Deposits
- Spring ApplicationContext事件机制:ApplicationEvent与ApplicationListener
- 多重继承
- 结构体字节对齐
- 异步|同步&阻塞|非阻塞
- python numpy的学习
- Ehcache配置详解及CacheManager使用
- python递归目录子目录列出目录和文件
- MongoDB学习
- SQL学习网站
- 生成随机字符串(UUID方法)
- php 用面向对象的方法对数据库增删改查
- 递归复制文件