zoukankan      html  css  js  c++  java
  • [leetcode]445. Add Two Numbers II

    不同于上题的地方是,这次链表的表示是前高位后低位

    这样的问题就是,要从后边开始加,但是链表不能访问到前一个节点,所以要用一个数据结构存数据,那肯定是栈喽

    同上一个题一样,要注意进位,进位不为空也要循环一次

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            if (l1==null&&l2==null) return null;
            Stack<Integer> s1 = new Stack<>();
            Stack<Integer> s2 = new Stack<>();
            ListNode list = new ListNode(0);
            while (l1!=null)
            {
                s1.push(l1.val);
                l1 = l1.next;
            }
            while (l2!=null)
            {
                s2.push(l2.val);
                l2 = l2.next;
            }
            int sum = 0;
            while (!s1.isEmpty()||!s2.isEmpty()||sum!=0)
            {
                if (!s1.isEmpty()) sum+=s1.pop();
                if (!s2.isEmpty()) sum+=s2.pop();
                list.val = sum%10;
                ListNode h = new ListNode(0);
                h.next = list;
                list = h;
                sum /=10;
            }
            return list.next;
        }
  • 相关阅读:
    一轮项目冲刺9
    一轮项目冲刺8
    一轮项目冲刺7
    一轮项目冲刺6
    一轮项目冲刺5
    一轮项目冲刺4
    一轮项目冲刺3
    一轮项目冲刺2
    一轮项目冲刺1
    移山小分队---每日记录01
  • 原文地址:https://www.cnblogs.com/stAr-1/p/8447494.html
Copyright © 2011-2022 走看看