链表中两树相加java实现

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //由于操作需要从尾到头做,反转两个链表从头节点都尾节点逐个处理
        ListNode reverseL1 = reverse(l1);
        ListNode reverseL2 = reverse(l2);
        //创建结果链表,使用哨兵节点的方式方便后续的操作
        ListNode dummy = new ListNode(0);
        ListNode resultNext = dummy;
        int carry = 0;
        //遍历两个链表操作
        while(reverseL1 != null || reverseL2 != null){
            //首先取出值如果链表中的元素不是空就去该元素如果为空就为0
            int value1 = reverseL1 == null ? 0 : reverseL1.val;
            int value2 = reverseL2 == null ? 0 : reverseL2.val;
            //求出和以及余数
            int sum = value1 + value2 + carry;
            int resultValue = sum >= 10 ? sum - 10 : sum;
            carry = sum >= 10 ? 1 : 0;
            //创建节点链接到链表中
            ListNode node = new ListNode(resultValue,null);
            resultNext.next = node;
            resultNext = resultNext.next;
            //给两个链表的节点重新赋值
            reverseL1 = reverseL1 == null ? null : reverseL1.next;
            reverseL2 = reverseL2 == null ? null : reverseL2.next;
        }
        //如果余数不为0还需要创建一个节点
        if(carry != 0){
            ListNode node = new ListNode(1);
            resultNext.next = node;
        }
        //返回的结果是链表的反转
        return reverse(dummy.next);
    }

    //反转链表
    public ListNode reverse(ListNode head){
        ListNode cur = head;
        ListNode pre = null;
        while(cur != null){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值