题目如下:
You are giventwo non-empty linked lists representing two non-negativeintegers. The digits are stored in reverse order and each of their nodescontain a single digit. Add the two numbers and return it as a linked list.
You may assumethe two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4-> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
题目大意:给你两个非空的链表,链表中不存在负数,数字以相反的顺序存储,每个节点包含一个位数,将两组数相加返回一个链表。
例如: Input: (2-> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8
/**
* 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) {
}
};
解题思路:首先定义一个链表result(刚开始只是一个节点)用于输出,将给定的两个链表的节点数据进行一一对应相加,考虑进位情况,相加的结果除10取余放入新的节点中,然后同样处理下一个节点数据,直到链表的下一个节点为NULL。具体的流程见程序:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
//定义一个链表result用于输出
ListNode *result = new ListNode(0);
ListNode *temp = result;// temp 用于处理数据
int interge = 0;//进位信息
int sum = 0;
while (l1&&l2)
{
sum = (l1->val + l2->val) % 10 + interge;
interge = (l1->val + l2->val) / 10;
l1 = l1->next; //将下一个节点赋给l1
l2 = l2->next; //将下一个节点赋给l2
temp->next = new ListNode(sum);//定义新节点
temp = temp->next;
}
return result->next;
}
};
如有错误请大家批评指正