leetcode 445. 两数相加 II java

leetcode 445. 两数相加 II java

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

你可以假设除了数字 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; }
 * }
 */
import java.util.*;
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stack<Integer> s1 = new Stack<Integer>();
        Stack<Integer> s2 = new Stack<Integer>();
        Stack<Integer> s3 = new Stack<Integer>();
        
        //数据存入栈
        while (l1 != null) { 
            s1.push(l1.val); 
            l1 = l1.next; 
        }
        while (l2 != null) { 
            s2.push(l2.val); 
            l2 = l2.next; 
        }
        
        int add = 0;
        //新建链表
        ListNode head = null, next = null;
        //结果写入栈
        while(s1.size() != 0 || s2.size() != 0)
        {
            int x = s1.size() != 0 ? s1.pop() : 0;
            int y = s2.size() != 0 ? s2.pop() : 0;
            int num = (x + y + add) % 10;
            add = (x + y + add)  / 10;
            s3.push(num);
        }
        //结果存入链表
        if(add != 0) 
            s3.push(add);
        if (s3.size() != 0) 
            head = new ListNode(s3.pop());
        next = head;
        while(s3.size() != 0)
        {
            ListNode n = new ListNode(s3.pop());
            next.next = n;
            next = n;

        }
        return head;
    }
}

在这里插入图片描述

发布了32 篇原创文章 · 获赞 13 · 访问量 8321

猜你喜欢

转载自blog.csdn.net/qq_23858785/article/details/97522561