题面:
2. Add Two Numbers
DescriptionHintsSubmissionsDiscussSolution
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
题意:给定两个反序列表,首位是最低位,求两列表逐位相加后的反序列表结果。
解题:题意比较坑,反序是一点,输出要不要反回来也没有说,最坑的是还有一组[2,4,3][5,6,4]的数据,正加反加的结果都是[8,0,7],着实有点绕,但输出又要反序,即[7,0,8]。其实也就是低位在前,逐位相加后输出,考察的是链表的基本操作。
代码:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int flag=0;
ListNode * tmp;
tmp=NULL;
while(l1||l2){
if(l1){
flag+=l1->val;
l1=l1->next;
}
if(l2){
flag+=l2->val;
l2=l2->next;
}
ListNode * x=new ListNode(0);
x->val=flag%10;
x->next=tmp;
tmp=x;
flag/=10;
}
if(flag){
ListNode * x=new ListNode(0);
x->val=flag;
x->next=tmp;
tmp=x;
}
return tmp;
}
};