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.
这一下就考到了我上学期才学的数据结构,刚好线性表也是学得一塌糊涂。只记得有一个结点ListNode,ListNode里面重要的是有一个next指向下一个ListNode,然后还可以自定义一些其他的数据域。
注释里面给出了单链表结点的定义:
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
结点带了一个值value和指向下一个结点的指针next,然后构造函数的唯一参数传值x给value,一个基本的定义。
大概了解了ListNode就好做了,下面是代码:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *res=new ListNode(-1);
ListNode *cur=res;
int carry=0;
while(l1||l2){
int n1=l1?l1->val:0;
int n2=l2?l2->val:0;
int sum=n1+n2+carry;
carry=sum/10;
cur->next=new ListNode(sum%10);
cur=cur->next;
if(l1)
l1=l1->next;
if(l2)
l2=l2->next;
}
if(carry)
cur->next=new ListNode(1);
return res->next;
}
};
思路是:
- 首先,设一个carry来表示某位上两数字和大于9时需要进位1,初始值为0。
- 然后,只要两个数的结点上的数字不同时为0,就一直循环读数,从最低位开始遍历两个单链表的结点读取数字,如果为0,则由题可知这个数就是0,之后也就不需要再读这个单链表的后面结点的了;如果不为0就赋给n,再两个n和进位carry相加得到某位上的数字和。
- 接着,和除以10判断是否进位,>=10就是1,否则为0。
- 同时,和膜10来得到相加后该位上的数字,并新建结点附在现在所在结点current的后面。
- 在完成一次循环前,移动三个链表,切记先建立好next,再把current指向next。
- 最后,在返回结果result的next指针之前,不要忘记判断carry还有没有值是否需要进位。