2.两个链表同一节点两数相加

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0); //新链表的头结点
        
        ListNode cur = head;            //用于移动

        int carry = 0; //存进位的
        while(l1 != null || l2 != null){
            int x = l1 != null ? l1.val : 0;
            int y = l2 != null ? l2.val : 0;
            
            int sum = x+y+carry;

            carry = sum/10;//大于10就取进位
            
            sum = sum%10; //个位

            cur.next = new ListNode(sum);

            cur = cur.next; //后移

            if(l1 != null ){
                l1 = l1.next;
            }
            if(l2 != null){
                l2 = l2.next;
            }
        }
        if(carry == 1){
            cur.next = new ListNode(carry);
        }
        return head.next;
    }
}

 

posted @ 2023-05-27 01:07  Lee最好好好吃饭  阅读(18)  评论(0)    收藏  举报