leetcode-----两个列表相加(Add Two Numbers)

1、问题描述

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

有两个单链表,代表两个非负数,每一个节点代表一个数位,数字是反向存储的,即第一个结点表示最低位,最后一个结点表示最高位。求两个数的相加和,并且以链表形式返回。 

2、思路

对两个链表都从第一个开始处理,进行相加,结果再除以10求商,作为下一位相加的进位,同时记录余数,作为本位的结果,一直处理,直到所有的结点都处理完。 

时刻注意进位!!!!!!

3、代码实现

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode li = null;
        ListNode node = null;
        int in = 0;
        while(l1!=null && l2!=null){
            int sum = l1.val + l2.val + in;
            int yu = sum % 10;
            if(node == null){
                node = new ListNode(yu);
                li = node;
            }else{
                node.next = new ListNode(yu);
                node = node.next;
            }
            in = sum / 10;
            l1 = l1.next;
            l2 = l2.next;
          
        }
        
        while(l1!=null){
            if(in != 0){
                int sum = l1.val + in;
                int yu1 = sum % 10;
                in = sum / 10;
                node.next = new ListNode(yu1);
                
            }else{
                 node.next = l1;
                 in = 0;
                
            }
            
           
            node = node.next;
            l1 = l1.next;
            
        }
       
         while(l2!=null){
            if(in != 0){
                int sum = l2.val + in;
                int yu1 = sum % 10;
                in = sum / 10;
                node.next = new ListNode(yu1);
                
            }else{
                 node.next = l2;
                in = 0;
                
            }
            
           
            node = node.next;
            l2 = l2.next;
            
        }
        if(l1==null && l2==null && in!=0){
            node.next = new ListNode(in);
        }
        return li;
        
    }
}

猜你喜欢

转载自blog.csdn.net/g1607058603/article/details/81037225