此题是链表中的两数相加,注意细节方法,每一个链表中的数只有一位,需要考虑进位问题
代码
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;
}
};
本文详细介绍了链表中两数相加的问题,包括处理进位和特殊情况。通过给出的代码实现,读者可以清晰地理解整个过程,并掌握解决类似问题的方法。
177

被折叠的 条评论
为什么被折叠?



