从零开始刷Leetcode day01 两数相加(Add Two Numbers)

两数相加(Add Two Numbers)-java解法

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

You are given two non-empty linked lists representing two non-negative integers. 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.You may assume the two numbers do not contain any leading zero, except the number 0 itself.

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

解法

  • 将两个链表看成是相同长度的进行遍历,如果一个链表较短则在前面补00,比如 987 + 23 = 987 + 023 = 1010
  • 设置进位标识位carry。每一位计算的同时需要考虑上一位的进位问题,而当前位计算结束后同样需要更新进位值
  • 如果两个链表全部遍历完毕后,进位值为 1,则在新链表最前方添加节点 1

- 复杂度分析

时间复杂度: O(max(m, n)),假设 m和n分别表示 l1和 l2的长度,上面的算法最多重复 max(m, n)次。
空间复杂度: O(max(m, n)),新列表的长度最多为max(m,n) +1。

代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(0);
        ListNode cur = dummyHead;
        int carry = 0;
        while(l1 != null || l2 != null){
            int x = l1 == null? 0:l1.val;
            int y = l2 == null? 0:l2.val;            
            int sum = (x+y+carry)%10;
            carry = (x+y+carry)/10;
            cur.next = new ListNode(sum);
            cur = cur.next;
            if(l1!= null){
                l1 = l1.next;
            }if(l2!= null){
                l2 = l2.next;
            }  
        }if(carry>0){
            cur.next = new ListNode(1);
        }
        return dummyHead.next;
    }
}

注意: 对于链表问题,返回结果为头结点时,通常需要先初始化一个伪头结点dummyHead,它的next指向真正的头结点head。使用dummyHead能够更好地初始化链表,从而避免链表构造过程需要指针移动,进而会导致头指针丢失,无法返回结果。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值