【力扣】445. 两数相加 II

题目:给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

进阶:

如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。

示例:

输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7

解答

/**
 * 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) {
    
    //利用栈存储链表的值
        if(l1.val == 0) return l2;
        if(l2.val == 0) return l1;
        Stack<Integer> s1 = new Stack<Integer>();
        Stack<Integer> s2 = new Stack<Integer>();
        ListNode l3 = new ListNode();
        while(l1 != null || l2 != null){
    
    
            if(l1 != null) {
    
    
                s1.push(l1.val);
                l1 = l1.next;
            }
            if(l2 != null) {
    
    
                s2.push(l2.val);
                l2 = l2.next;
            }
        }
        int count = 0;
        while(!s1.isEmpty() || !s2.isEmpty() || count > 0){
    
    
            int sum = count;
            if(!s1.isEmpty()) sum += s1.pop();
            if(!s2.isEmpty()) sum += s2.pop();
            if(sum >= 10){
    
    
                count = sum / 10;
                sum %= 10;
            }else count = 0;
            ListNode node = new ListNode(sum);
            node.next = l3.next;
            l3.next = node;
        }
        return l3.next;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44485744/article/details/105509267
今日推荐