[leetcode]445. Add Two Numbers II 两数相加II


You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

题目

俩数用链表表示,做个加法

思路

1. use stack to covert input list data

2. sum up from pop item from two stacks to a desired linkedlist

代码

 1 class Solution {
 2     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
 3         if (l1 == null && l2 == null) return null;
 4         if (l2 == null) return l1;
 5         if (l1 == null) return l2;
 6         // use stack to convert list's order
 7         Stack<Integer> s1 = new Stack<>();
 8         Stack<Integer> s2 = new Stack<>();
 9     
10         while (l1 != null) {
11             s1.push(l1.val);
12             l1 = l1.next;
13         }
14         
15         while (l2 != null) {
16             s2.push(l2.val);
17             l2 = l2.next;
18         }
19         
20         int sum = 0;
21         ListNode head = new ListNode(0);
22         // sum up to a new linkedlist
23         while (!s1.isEmpty() || !s2.isEmpty()) {
24             if (!s1.isEmpty()) sum += s1.pop();
25             if (!s2.isEmpty()) sum += s2.pop();
26             
27             int val = sum % 10;
28           
29             ListNode node = new ListNode(0);
30             head.val = val;
31             node.next = head;
32             head = node;
33             
34             sum /= 10;
35         }
36         if (sum == 0){
37             return head.next;
38         }
39         head.val = sum;
40         return head;
41     }
42 }
原文地址:https://www.cnblogs.com/liuliu5151/p/9828175.html