题目
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
分析
两个单链表的各个节点的数字相加,而且包括进位,那用一个变量carry保存进位就可以了。本体主要还是链表的使用,比如如何return ListNode*的节点。
这儿,我们先定义要输出的链表:
ListNode* result = new ListNode(0);
ListNode* temp = result;
输出链表这样就可以了:
return result->next;
还是比较简单的,temp 用于向下一个节点写值:
temp->next=new ListNode((a+b+carry)%10);
temp=temp->next;
代码
/**
* 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* result = new ListNode(0);
ListNode* temp = result;
int a,b,carry=0;
while(l1!=NULL || l2!=NULL){
a=0;
if(l1!=NULL){
a=l1->val;
l1=l1->next;
}
b=0;
if(l2!=NULL){
b=l2->val;
l2=l2->next;
}
temp->next=new ListNode((a+b+carry)%10);
carry=(a+b+carry)/10;
temp=temp->next;
}
if(carry==1){
temp->next= new ListNode(1);
}
return result->next;
}
};