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

本文介绍了一种使用递归方法解决两个链表表示的数字相加问题的算法。通过创建一个新的链表来存储结果,并考虑进位操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

  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     }

 

转载于:https://www.cnblogs.com/zhstudy/p/5980070.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值