此题是链表中的两数相加,注意细节方法,每一个链表中的数只有一位,需要考虑进位问题
代码
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode *head;
if(l1==NULL||l2==NULL)
return head;
head = new ListNode(0);
ListNode *p1, *p2, *q;
p1 = l1;
p2 = l2;
q = head;
int carry = 0;
while(p1!=NULL&&p2!=NULL)
{
ListNode *tempNode = new ListNode(0);
int tempVal = p1->val + p2->val + carry;
tempNode->val = tempVal%10;
carry = tempVal/10;
q->next = tempNode;
q = tempNode;
p1 = p1->next;
p2 = p2->next;
}
while(p1!=NULL)
{
ListNode *tempNode = new ListNode(0);
int tempVal = p1->val + carry;
tempNode->val = tempVal%10;
carry = tempVal/10;
q->next = tempNode;
q = tempNode;
p1 = p1->next;
}
while(p2!=NULL)
{
ListNode *tempNode = new ListNode(0);
int tempVal = p2->val + carry;
tempNode->val = tempVal%10;
carry = tempVal/10;
q->next = tempNode;
q = tempNode;
p2 = p2->next;
}
while(carry!=0)
{
ListNode *tempNode = new ListNode(0);
int tempVal = carry;
tempNode->val = tempVal%10;
carry = tempVal/10;
q->next = tempNode;
q = tempNode;
}
return head->next;
}
};