这里给出别人写的一段代码,很简洁,但是不易理解。。。
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
int x=0, y=0, carry=0, sum=0;
ListNode *h=NULL, **t=&h;
while (l1!=NULL || l2!=NULL){
x = getValueAndMoveNext(l1);
y = getValueAndMoveNext(l2);
sum = carry + x + y;
ListNode *node = new ListNode(sum%10);
*t = node;
t = (&node->next);
carry = sum/10;
}
if (carry > 0) {
ListNode *node = new ListNode(carry%10);
*t = node;
}
return h;
}
int getValueAndMoveNext(ListNode* &l){
int x = 0;
if (l != NULL){
x = l->val;
l = l->next;
}
return x;
}
下面给出自己的代码
其结果在最后也就是最高为处有个0,虽然对结果没什么影响,但是并不完美,
希望有懂得朋友给个解决方法
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) :val(x), next(NULL) {};
};
ListNode* addTwoNumbers(ListNode* p1, ListNode* p2)
{
ListNode* result =new ListNode(0);
ListNode* ptemp = result;
int carry = 0;
while (p1!=nullptr||p2!=nullptr)
{
int x =p1? p1->val:0;
int y =p2? p2->val:0;
int sum = x + y + carry;
carry = sum % 10;
ptemp->val=carry;
ListNode* temp=new ListNode(0);
ptemp->next = temp;
ptemp = ptemp->next;
carry = sum / 10;
if (p1!=nullptr)
p1 = p1->next;
if (p2!=nullptr)
p2 = p2->next;
}
if (carry == 1)
{
ListNode* temp = new ListNode(0);
temp->val = 1;
ptemp->next = temp;
}
return result;
}
int main()
{
ListNode* p1 = new ListNode(2);
ListNode* p2 = new ListNode(4);
ListNode* p3 = new ListNode(3);
p1->next = p2;
p2->next = p3;
p3->next = nullptr;
ListNode* p4 = new ListNode(5);
ListNode* p5 = new ListNode(6);
ListNode* p6 = new ListNode(4);
ListNode* p7 = new ListNode(1);
p4->next = p5;
p5->next = p6;
p6->next = p7;
p7->next = nullptr;
ListNode* result = addTwoNumbers(p1, p4);
while (result)
{
cout << result->val << endl;
result=result->next;
}
return 0;
}
“`