LeetCode.2_[链表]_两数相加

1. 题目

在这里插入图片描述

2.解题思路

找到长度长的链表,把短链表的值直接加到长链表对应的值上,之后判断长链表的值是否大于9,大于则进位,如果后一位为空,得添加一个节点
在这里插入图片描述

3.代码实现

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head1 = l1;
		ListNode head2 = l2;
		ListNode first = new ListNode(0);
		int count1 = 0, count2 = 0;
		while(head1 != null) {
			count1++;
			head1 = head1.next;
		}
		while(head2 != null) {
			count2++;
			head2 = head2.next;
		}
		if(count1 > count2)	{
			head1 = l1;
			first = l1;
			head2 = l2;
		}else {
			head1 = l2;
			first = l2;
			head2 = l1;
		}
		ListNode head = first;
		while(head2 != null) {
			head1.val += head2.val; 
			head1 = head1.next;
			head2 = head2.next;
		}
		while(first != null) {
			if(first.val > 9) {
				int shi = first.val / 10;
				first.val %= 10;
				if(first.next == null) {
					ListNode next = new ListNode(shi);
					first.next = next;
				}else {
					first.next.val += shi;
				}
			}
			first = first.next;
		}
		
		
		return head;
    }
}

4.解法拓展

再建一个链表,将两个链表的值相加,短链表结束之后,将短链表的值设为0,长链表每次加短链表的值就是长链表的值,设置carry,进位了carry=1,没进位=0

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummyHead = new ListNode(0);
    ListNode p = l1, q = l2, curr = dummyHead;
    int carry = 0;
    while (p != null || q != null) {
        int x = (p != null) ? p.val : 0;
        int y = (q != null) ? q.val : 0;
        int sum = carry + x + y;
        carry = sum / 10;
        curr.next = new ListNode(sum % 10);
        curr = curr.next;
        if (p != null) p = p.next;
        if (q != null) q = q.next;
    }
    if (carry > 0) {
        curr.next = new ListNode(carry);
    }
    return dummyHead.next;
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/add-two-numbers/solution/liang-shu-xiang-jia-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值