题目
2. Add Two Numbers
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.
给出两个非空链表,表示两个非负整数。这些数字以相反的顺序存储,每个节点都包含一个数字。添加两个数字的值并将其作为链表返回。
假定两个数字不包含任何前导零,除了数字0本身。
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
分析
本题要求给出一个方法addTwoNumbers,方法要求:
传入两个参数:l1,l2(两个链表头)。
传出结果链表的表头。
本题只需同时遍历l1,l2,将两个链表位置上一一对应的元素相加,添加到新链表中即可。
题解
java实现
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode answer = new ListNode(0);
ListNode tmp = answer;
int carry = 0;
while(l1 != null || l2!=null){
tmp.next = new ListNode(0);
tmp = tmp.next;
int value1 = l1==null?0:l1.val;//如果l2遍历结束前,l1先遍历完,就假定l2的后续元素的val均为0
int value2 = l2==null?0:l2.val;//如果l1遍历结束前,l2先遍历完,就假定l2的后续元素的val均为0
int sum = value1 + value2;
if(sum + carry>=10){
tmp.val = sum - 10 + carry;
carry = 1;
}else{
tmp.val = sum + carry;
carry = 0;
}
l1 = l1==null?l1:l1.next;//小心空指针异常!
l2 = l2==null?l2:l2.next;
}
//while循环处理完之后,l1和l2都已经被遍历完了,但可能还多一个进位没有处理
if(carry==1){
tmp.next = new ListNode(1);
}
return answer.next;//之所以是传出answer.next,把answer看作一个没有值的表头来处理,仅仅是为了整体代码简洁方便。
}
c++实现
前面java实现代码并没有用到什么c++里没有的api,所以直接从java照搬思路就行。无非就是把l1.next
改成了l1 -> next
,没有多少分别。
这里贴一个网友的解答,思路基本一样,只是代码经过整理后更简洁美观一些:
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;
}
};