leetcode 445. 两数相加 II【栈】

题目要求不能翻转链表,因此可以考虑遍历链表,然后将链表数据一次放入栈中,这样当元素出栈时,自动实现了个位的对齐。
然后定义一个变量记录进位即可。注意结果链表的插入使用头插法,这样插入完成后不用再对齐进行翻转。

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stack<Integer> s1 = new Stack<>();
        Stack<Integer> s2 = new Stack<>();

        while(l1!=null){
            s1.push(l1.val);
            l1 = l1.next;
        }
        while(l2!=null){
            s2.push(l2.val);;
            l2 = l2.next;
        }
        
        ListNode head = null;
        int carry=0;
        while(!s1.isEmpty() || !s2.isEmpty() || carry!=0){
            int num1 = s1.isEmpty()?0:s1.pop();
            int num2 = s2.isEmpty()?0:s2.pop();
            int num = num1+num2+carry;
            carry = num/10;
            num = num%10;
            ListNode temp = new ListNode(num);
            temp.next = head;
            head = temp;
        }
        return head;
    }
}
发布了55 篇原创文章 · 获赞 0 · 访问量 760

猜你喜欢

转载自blog.csdn.net/er_ving/article/details/105521862
今日推荐