Leetcode两数相加

  1. 两数相加
    给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。

请你将两个数相加,并以相同形式返回一个表示和的链表。

你可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例 1:

输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.
示例 2:

输入:l1 = [0], l2 = [0]
输出:[0]
示例 3:

输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]

提示:

每个链表中的节点数在范围 [1, 100] 内
0 <= Node.val <= 9
题目数据保证列表表示的数字不含前导零

/**

  • 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 retListNode = new ListNode();
     ListNode preNode = retListNode;
     ListNode retNode = retListNode;
     ListNode l1Iter = l1;
     ListNode l2Iter = l2;
     int val = -1;
     int addOne = 0;
     while(l1Iter != null && l2Iter != null){
         addOne = 0;
         val = l1Iter.val + l2Iter.val + retListNode.val;
         if(val >= 10){
             val = val - 10;
             addOne = 1;
         }
    
         retListNode.val = val;
         
    
         ListNode node = new ListNode();
         node.next = null;
         node.val = addOne;
         
         retListNode.next = node;
         preNode = retListNode;
         retListNode = retListNode.next;
         
         l1Iter = l1Iter.next;
         l2Iter = l2Iter.next;
     }
    
     if(l1Iter != null){
         while(l1Iter != null){
             addOne = 0;
             val = l1Iter.val + retListNode.val;
             if(val >= 10){
                 val = val - 10;
                 addOne = 1;
             }
    
             retListNode.val = val;
             
    
             ListNode node = new ListNode();
             node.next = null;
             node.val = addOne;
             retListNode.next = node;
             preNode = retListNode;
             retListNode = retListNode.next;
             l1Iter = l1Iter.next;
         }
     }
    
     if(l2Iter != null){
         while(l2Iter != null){
             addOne = 0;
             val = l2Iter.val + retListNode.val;
             if(val >= 10){
                 val = val - 10;
                 addOne = 1;
             }
    
             retListNode.val = val;
             
    
             ListNode node = new ListNode();
             node.next = null;
             node.val = addOne;
             retListNode.next = node;
             preNode = retListNode;
             retListNode = retListNode.next;
             l2Iter = l2Iter.next;
         }
     }
    
    
     if(preNode.next != null && preNode.next.val == 0){
         preNode.next = null;
     }
    
     return retNode;
    

    }
    }

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页