• 【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     }
  • 相关阅读:
    SecureCRT
    MySQL
    流式计算概述
    WEB加密算法
    drop、truncate和delete的区别
    JVM参数
    HTTP1.0与HTTP1.1区别
    HTTP请求方法
    Java查看JVM转态的命令总结
    go二次更新
  • 原文地址:https://www.cnblogs.com/zhstudy/p/5980070.html
Copyright © 2020-2023  润新知