链表相加-

该代码实现了一个方法,首先反转两个链表,然后逐位相加节点值,当和超过10时进行进位,最后再反转生成的新链表。

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

 思路:创建一个ReverseList方法,然后将开头每个值相加,当和超过十时则进一,并加到链表下一个数上,最后将生成的链表进行反转;

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */



public class Solution {
    /**
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    public ListNode ReverseList(ListNode pHead){
        if(pHead == null){
            return null;
        }
        ListNode cur = pHead;
        ListNode pre = null;
        while(cur != null){
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
    public ListNode addInList (ListNode head1, ListNode head2) {
        if(head1 == null){
            return head2;
        }
        if(head2 == null){
            return head1;
        }
        head1 = ReverseList(head1);
        head2 = ReverseList(head2);
        ListNode res = new ListNode(-1);
        ListNode head = res;
        int carry = 0;
        while(head1 != null || head2 != null || carry != 0){
            int k1 = head1 == null ? 0 : head1.val;
            int k2 = head2 == null ? 0 : head2.val;
            int temp = k1 + k2 + carry;
            carry = temp / 10;
            temp %= 10;
            head.next = new ListNode(temp);
            head = head.next;
            if(head1 != null){
                head1 = head1.next;
            }
            if(head2 != null){
                head2 = head2.next;
            }
        }
        return ReverseList(res.next);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值