LintCode167:链表的求和
2017-10-27 20:09
197 查看
题目描述
你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。测试样例
给出两个链表 3->1->5->null 和 5->9->2->null,返回 8->0->8->null
解题思路
这道题和大整数加减法类似。三个while循环,最后加上进位是否大于0的判断。第一个循环 while(list1 != NULL && list2 != NULL)
第二个循环 while(list1 != NULL)
第三个循环 while(list2 != NULL)
最后别忘了判断进位是否大于0。
这里:
int sum = (list1->val + list2->val + up) % 10;
up = (list1->val + list2->val + up) / 10;
代码如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: /* * @param list1: the first list * @param list2: the second list * @return: the sum list of list1 and list2 */ ListNode * addLists(ListNode * list1, ListNode * list2) { // write your code here ListNode *head = new ListNode(-1); ListNode *pNow = head; int up = 0; while (list1 != NULL && list2 != NULL) { int sum = (list1->val + list2->val + up) % 10; up = (list1->val + list2->val + up) / 10; ListNode *temp = new ListNode(sum); pNow->next = temp; pNow = pNow->next; list1 = list1->next; list2 = list2->next; } while (list1 != NULL) { int sum = (list1->val + up) % 10; up = (list1->val + up) / 10; ListNode *temp = new ListNode(sum); pNow->next = temp; pNow = pNow->next; list1 = list1->next; } while (list2 != NULL) { int sum = (list2->val + up) % 10; up = (list2->val + up) / 10; ListNode *temp = new ListNode(sum); pNow->next = temp; pNow = pNow->next; list2 = list2->next; } if (up > 0) { ListNode *temp = new ListNode(up); pNow->next = temp; pNow = pNow->next; } return head->next; } };
相关文章推荐
- 链表多项式求和
- 167. 链表求和(add-two-numbers)(c++)----lintcode面试题之链表
- 容易_167_链表求和(3)
- 数据结构实践——链表:多项式求和
- 链表求和
- lintcode 167 链表求和
- LintCode:链表求和
- 一元多项式求和(Java链表实现)
- 167 - 链表求和
- 算法#25--两整数链表求和
- 链表求和
- lintcode add-two-numbers 链表求和
- 数据结构 第二章 单链表应用举例——一元多项式求和(待补充)
- 链表求和
- 蓝桥杯 ALGO-107 算法训练 9-7链表数据求和操作
- Leetcode 2. Add Two Numbers(链表求和)
- java用多线程进行链表求和器
- [Lintcode] #167 链表求和
- Java实现-链表求和2
- 链表求和