面试题02.05 链表求和

在这里插入图片描述

思路  遍历,当一个链表为空时,置0于另一个链表及进位符想加
当最高位产生进位时,根据carry位的状态 ,增加一个节点。




/**
 * 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) {
    
    
        int carry = 0;
        ListNode sum1 = new ListNode(0,l1);
        ListNode cur = sum1;
        if(l1==null){
    
    
            return l2;
        }
        if(l2==null){
    
    
            return l1;
        }
        while(l1!=null||l2!=null){
    
    
            int sum = 0;
            if(l1==null){
    
    
                sum = l2.val + carry;
            }
            if(l2==null){
    
    
                sum = l1.val +carry;
            }
            if(l1!=null&&l2!=null){
    
    
                sum = l1.val + l2.val +carry;
            }
            carry = sum/10;
            sum = sum % 10;
            ListNode a = new ListNode(sum);
            sum1.next = a;
            sum1 = sum1.next;
            if(l1!=null){
    
    
                l1 = l1.next;
            }
            if(l2!=null){
    
    
                l2 = l2.next;
            }
        }
        if(carry==1){
    
    
            ListNode a = new ListNode(1);
            sum1.next = a;
        }
        return cur.next;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40310710/article/details/112912645