• 【LeetCode】2.Add Two Numbers 链表数相加


    题目:

      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

    思路:采用递归思想。设置一个carray变量用于存放进位值,将l1,l2,carray相加,十进制取余得到该位的值,进行链表下一位运算。

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    11         return addTwoNumbersHelp(l1,l2,0);
    12     }
    13     
    14     public ListNode addTwoNumbersHelp(ListNode l1,ListNode l2,int carray){
    15         if(l1==null && l2==null){
    16             return carray==0?null:new ListNode(carray);
    17         }
    18         
    19         if(l1==null && l2!=null){
    20             l1=new ListNode(0);
    21         }
    22         
    23         if(l1!=null && l2==null){
    24             l2=new ListNode(0);
    25         }
    26         
    27         int sum=l1.val+l2.val+carray;
    28         ListNode curr=new ListNode(sum%10);
    29         curr.next=addTwoNumbersHelp(l1.next,l2.next,sum/10);
    30         
    31         return curr;
    32     }
  • 相关阅读:
    Java入门
    Android Gradle plugin requires Java 11 to run. You are currently using Java 1.8
    pypy3.8安装
    asyncio执行阻塞代码
    linux安装go
    python消费rabbitmq
    绑定进程到指定cpu运行
    负载均衡算法
    django版本规划
    FastAPI WebSocket 简单演示
  • 原文地址:https://www.cnblogs.com/zhstudy/p/5980070.html
Copyright © 2020-2023  润新知