2. Add Two Numbers
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
解题思路:
这道题没什么难度,需要注意以下几点:
1.要注意进位是向后的;
2.链表l1或l2为空时,直接返回,这是边界条件,省掉多余的操作;
3.链表l1和l2长度可能不同,因此要注意处理某个链表剩余的高位;
4.2个数相加,可能会产生最高位的进位,因此要注意在完成以上1-3的操作后,判断进位是否为0,不为0则需要增加结点存储最高位的进位。
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null && l2 == null)
return null;
ListNode head = new ListNode(0);//用来存放结果
ListNode point = head;
int carry = 0;//进位
while(l1 != null && l2 != null){
int sum = carry + l1.val + l2.val;
point.next = new ListNode(sum % 10);
carry = sum / 10;
l1 = l1.next;
l2 = l2.next;
point = point.next;
}
while(l1 != null){
int sum = carry + l1.val;
point.next = new ListNode(sum % 10);
carry = sum / 10;
l1 = l1.next;
point = point.next;
}
while(l2 != null){
int sum = carry + l2.val;
point.next = new ListNode(sum % 10);
carry = sum / 10;
l2 = l2.next;
point = point.next;
}
if(carry != 0){
point.next = new ListNode(carry);
}
return head.next;
}
}