您的位置:首页 > 编程语言 > C语言/C++

leetcode-solution C++【2】---add two numbers

2018-01-29 21:02 615 查看
原题

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.

Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

比较简单,就是两个链表相加,这里要注意进位的问题,以及最高位相加是否大于10

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode list(0);
ListNode *p=&list;
//ListNode* p = new ListNode(0);
//ListNode* newhead = p;

int cn=0;
while(l1||l2)
{
int val=cn+(l1 ? l1->val : 0)+(l2 ? l2->val : 0);
cn=val/10;
val=val%10;
p->next=new ListNode(val);
p=p->next;
if(l1)
l1=l1->next;
if(l2)
l2=l2->next;
}
if(cn!=0)
{
p->next=new ListNode(cn);
p=p->next;
}
return list.next;
}
};

先写在这里,具体细节 后面再添加
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode C 链表相加