leetcode445 Add Two Numbers II java
2017-03-11 10:38
351 查看
Description
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
解法
用栈可以很方便解决。public ListNode addTwoNumbers(ListNode l1, ListNode l2) { Stack<Integer> stack1 = new Stack<>(); Stack<Integer> stack2 = new Stack<>(); while(l1 != null) { stack1.push(l1.val); l1 = l1.next; } while(l2 != null) { stack2.push(l2.val); l2 = l2.next; } ListNode result = new ListNode(0); int carry = 0; while(!(stack1.isEmpty() && stack2.isEmpty())) { int num1 = stack1.isEmpty() ? 0 : stack1.pop(); int num2 = stack2.isEmpty() ? 0 : stack2.pop(); result.val = (num1 + num2 + carry) % 10; carry = (num1 + num2 + carry) / 10; ListNode head = new ListNode(carry); head.next = result; result = head; } return result.val == 0 ? result.next : result; }
相关文章推荐
- [leetcode445】Add Two Numbers II
- Add Two Numbers II || LeetCode-445
- leetcode 445 Add Two Numbers II C++
- leetcode445~Add Two Numbers II
- Sum—LeetCode-445 Add Two Numbers II
- LeetCode - 445 - Add Two Numbers II
- 【leetcode 445】Add Two Numbers II
- LeetCode 445 Add Two Numbers II
- LeetCode 445 Add Two Numbers II(栈+链表)
- LeetCode 2: Add Two Numbers (JAVA)
- <LeetCode(Java版)>Add Two Numbers
- LeetCode(java)2. Add Two Numbers
- leetcode 练习——add two numbers (Java)
- Leetcode 2 Add Two Numbers Java
- leetcode:Add Two Numbers---------java源码
- LeetCode : Add Two Numbers [java]
- LeetCode 2 - Add Two Numbers ( JAVA )
- LeetCode_2_AddTwoNumbers(Java Code)
- Java Leetcode Add Two Numbers
- leetcode 002 Add Two Numbers(java)