2. Add Two Numbers(Java)

题目: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

解析:给两个链表,求和,注意进位(变量carry)。需要考虑两种情况:

  • 两个链表长度一致
  • 两个链表长度不一致(短链表缺少的节点补零处理)
 /**
  * 如果两个不一样长,则补零
  */
public class Solution {
    public ListNode addTwoNumbers(ListNode a, ListNode b) {
        if(a==null && b==null) return null;
        if(a==null) return b;
        if(b==null) return a;
        ListNode cura=a,curb=b;
        ListNode head=new ListNode(-1),cur=head;
        
        int carry=0;
        while(cura!=null || curb!=null){
            int val_a=cura!=null?cura.val:0;//如果是空,用0
            int val_b=curb!=null?curb.val:0;//如果是空,用0
            int sum=val_a+val_b+carry;

            cur.next=new ListNode(sum%10);
            carry=sum/10;
            cur=cur.next;
            
            cura=cura!=null?cura.next:null;//!!注意,设为null
            curb=curb!=null?curb.next:null;
        }
        
        if(carry!=0){
          cur.next=new ListNode(carry);//如果最高位有进位
        }
        return head.next;
    }
}



你可能感兴趣的:(leetecode)