两链表数相加问题
【题目描述】
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
【Example】
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
【思路】
链表表示的整数,链表头代表整数的个位数,链表尾部代表这个整数最高位,所以两个整数相加就是对应两个链表从表头开始遍历相加 ,并判断是否进位,得到的也是一个用链表表示的整数,所以同时遍历两个链表并将值相加,再考虑进位,具体代码如下:
/**
* 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* sl = new ListNode(0); //存储结果的链表
ListNode* current = sl; //进行操作的链表
int over = 0; //进位
while(l1 || l2){
int sum = ( l1? l1->val:0 )+(l2?l2->val:0) +over;
current->next = new ListNode(sum%10);
over = sum/10;
current = current->next;
l1 = l1?l1->next:NULL;
l2 = l2?l2->next:NULL;
}
//判断是否最高位还需要进位,比如两位数加两位数可能结果为三位数
if(over != 0){
current->next = new ListNode(over);
}
return sl->next;
}
};