题目描述
你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。
测试样例
给出两个链表 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;
}
};