[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;
    }

 

posted @ 2018-02-13 21:55  stAr_1  阅读(117)  评论(0编辑  收藏  举报