Leetcode OJ 2 Add Two Numbers
题目描述:
You are given two non-empty linked lists representingtwo non-negative integers. The digits are stored in reverse order and each oftheir nodes contain a single digit. Add the two numbers and return it as alinked list.
You may assume the two numbers do not contain anyleading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
题目理解:
给定两个非空链表,分别代表两个非负整数,该数字被倒序存放,每个节点代表一位数字。将两个数字相加,返回新的代表新数字的链表。
假设两个数字不包含任何前导0,除了0本身
测试用例:
功能测试:两个链表不一样长;两数字之和存在额外的进位(99,1);
特殊输入:其中一个链表是空;
解答:
1. 从两个链表的头开始,每一位的数字对应相加,并加上上一位的进位,保留个位数字,十位数字表示进位用于下一个节点相加;
2. 对每个节点都进行相同的上述操作,因此用循环;
3. 当l1或者l2同时为null时进行如下循环:
4. 计算两个数字与进位相加之和sum,考虑l1和l2为空的情况;
5. 新建一个节点curr_node,设置此节点的值为sum的个位数字;
6. 设置curr_node的前节点pre_node的指针指向该节点;
7. 将当前的节点curr_node赋值给pre_node,计算进位carry,调整l1、l2的节点,用作下一次的循环;
8. 循环结束,即两个链表的每位数字都相加过后,可能有额外的进位,这时增加判断语句,如果有额外的进位,则新建节点,值为进位值carry,并将pre_node的指针指向新建节点;
9. 在循环之初,pre_node初始化为ListNode(0),并且赋值给head_node;
10. 因此返回的是head_node.next,它是链表l1、l2真正相加时的第一个数字;
public class Solution {
public ListNodeaddTwoNumbers(ListNode l1, ListNode l2) {
if(l1 ==null && l2 == null) return null;
ListNode pre_node = new ListNode(0);
ListNode head_node = pre_node;
int carry= 0;
while(l1 !=null || l2 != null){
int sum = 0;
if(l1 ==null){
sum = l2.val + carry;
}
else if(l2 ==null){
sum = l1.val + carry;
}
else
sum = l1.val + l2.val + carry;
ListNode curr_node = new ListNode(0);
curr_node.val = sum % 10;
carry = sum / 10;
pre_node.next = curr_node;
pre_node = curr_node;
if(l1 !=null) l1 = l1.next;
if(l2 !=null) l2 = l2.next;
}
if(carry> 0){
pre_node.next = new ListNode(carry);
};
return head_node.next;
}
}