445. Add Two Numbers II

本文介绍了一种不改变原链表的情况下实现链表加法的方法。通过使用栈来反转链表,进行逐位相加,并生成新的链表表示结果。

题目

原始地址:https://leetcode.com/problems/add-two-numbers-ii/#/description
e4ad2195gy1fff84t9aogj21300cemyt.jpg

/**
 * 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) {
        
    }
}

描述

给定两个单链表,代表两个非负整数,链表的头节点代表数的最高位。求这两个数的和并且以相同的链表形式返回。

分析

一种常用的解法是分别将两个链表反转,低位在前高位在后,这样符合加法的常规做法。但是本题目要求不得修改原链表,那么我们就新申请两个栈用来做一下反转,逐位相加后生成新链表作为结果返回。

解法

/**
 * 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) {
        Stack<Integer> s1 = new Stack<>(), s2 = new Stack<>(), s3 = new Stack<>();
        while (l1 != null) {
            s1.push(l1.val);
            l1 = l1.next;
        }
        while (l2 != null) {
            s2.push(l2.val);
            l2 = l2.next;
        }
        int carry = 0;
        while (!s1.empty() || !s2.empty() || carry != 0) {
            int v1 = s1.empty() ? 0 : s1.pop();
            int v2 = s2.empty() ? 0 : s2.pop();
            int sum = v1 + v2 + carry;
            s3.push(sum % 10);
            carry = sum / 10;
        }
        ListNode head = new ListNode(0), node = head;
        while (!s3.empty()) {
            node.next = new ListNode(s3.pop());
            node = node.next;
        }
        return head.next;
    }
}

转载于:https://www.cnblogs.com/fengdianzhang/p/6831640.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值