LeetCode#2. Add Two Numbers

本文介绍了一种链表求和的算法实现,该算法能够处理两个逆序存储非负整数的链表,并以逆序形式返回它们的和。文章提供了两种实现方式:一种是通过同时移动两个指针并处理不同长度链表的情况;另一种是在其中一个链表为空时为其添加值为0的节点。

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

  • 题目:给定两个非空的链表,存储的是两个非负整数,以逆序的形式存储这两个数的每一个元素,求这两个数之和,并且也以逆序返回

    例子:342+465的存储形式为
    (2->4->3)和 (5->6->4)
    返回结果为:(7->0->8)

  • 思路:首先这一题不需要判空。
    这一题只需要考虑两个问题:

    • 进位
    • 链表长度不同

    对于进位:只需要用一个变量carry来记录,但不要忘了两个链表最尾部进位问题(即最后carry不为0的话,需要再多加一个结点)

    对于链表长度:

    * 或者 两个指针同时移动,一旦有指针为空,退出当前循环;之后对不为空的链表进行处理
    * 递归补值为0的节点
    
  • 代码一:(指针同时移动,某个链表为空,则退出while循环)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
       ListNode newHead = new ListNode(0);
       ListNode node = newHead;
       int carry = 0;
       while(l1 != null && l2 != null){
           int value = l1.val + l2.val + carry;
           carry = value/10;
           node.next = new ListNode(value%10);
           node = node.next;
           l1 = l1.next;
           l2 = l2.next;
       }
       while(l1 != null){
           int value = carry + l1.val;
           carry = value/10;
           node.next = new ListNode(value%10);
           node = node.next;
           l1 = l1.next;
       }
       while(l2 != null){
           int value = carry + l2.val;
           carry = value/10;
           node.next = new ListNode(value%10);
           node = node.next;
           l2 = l2.next;
       }

       if(carry != 0){
           node.next = new ListNode(carry);
       }

       return newHead.next;
    }
}
  • 代码二:(当其中一个链表不为空时,为空的链表加上值为0的节点)
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int carry = 0;
        return helper(l1, l2, carry);
    }

    private ListNode helper(ListNode l1, ListNode l2, int carry){
        if(l1 == null && l2 == null){
            if(carry != 0){
                ListNode curr = new ListNode(carry);
                return curr;
            }else{
                return null;
            }
        }
        if(l1 == null && l2 != null){
            l1 = new ListNode(0);
        }
        if(l2 == null && l1 != null){
            l2 = new ListNode(0);
        }

        int value = l1.val + l2.val + carry;
        carry = value/10;
        ListNode curr = new ListNode(value%10);
        curr.next = helper(l1.next, l2.next, carry);
        return curr;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值