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
增加一个flag标记位,用来保存进位。
代码如下:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if(!l1) return l2;
if(!l2) return l1;
ListNode *result=new ListNode(0);
ListNode *p;
p=result;
int flag=0;
while(l1!=NULL && l2!=NULL){
p->next=new ListNode((flag+l1->val+l2->val)%10);
flag=(flag+l1->val+l2->val)/10;
l1=l1->next;
l2=l2->next;
p=p->next;
}
while(l1!=NULL){
p->next=new ListNode((flag+l1->val)%10);
flag=(flag+l1->val)/10;
l1=l1->next;
p=p->next;
}
while(l2!=NULL){
p->next=new ListNode((flag+l2->val)%10);
flag=(flag+l2->val)/10;
l2=l2->next;
p=p->next;
}
if(flag>0) p->next=new ListNode(flag);
return result->next;
}
};
感觉写的复杂了,在讨论区看了potpie的答案,思路一样,代码简洁很多,值得学习:
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode c1 = l1;
ListNode c2 = l2;
ListNode sentinel = new ListNode(0);
ListNode d = sentinel;
int sum = 0;
while (c1 != null || c2 != null) {
sum /= 10;
if (c1 != null) {
sum += c1.val;
c1 = c1.next;
}
if (c2 != null) {
sum += c2.val;
c2 = c2.next;
}
d.next = new ListNode(sum % 10);
d = d.next;
}
if (sum / 10 == 1)
d.next = new ListNode(1);
return sentinel.next;
}
}