题目:
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
链接:https://leetcode.com/problems/add-two-numbers-ii/#/description
4/16/2017
61ms, 69%
其实本来想先遍历再来解决,后来发现说不能反转,哈哈那就用stack来代替好了
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 11 if (l1 == null) return l2; 12 else if (l2 == null) return l1; 13 14 Stack<ListNode> s1 = new Stack<ListNode>(); 15 Stack<ListNode> s2 = new Stack<ListNode>(); 16 ListNode ret = null; 17 18 while (l1 != null) { 19 s1.push(l1); 20 l1 = l1.next; 21 } 22 while (l2 != null) { 23 s2.push(l2); 24 l2 = l2.next; 25 } 26 int carry = 0; 27 while (!s1.empty() || !s2.empty() || carry != 0) { 28 int val = (s1.empty()? 0: s1.pop().val) + (s2.empty()? 0: s2.pop().val) + carry; 29 ListNode t = new ListNode(val % 10); 30 t.next = ret; 31 ret = t; 32 carry = val / 10; 33 } 34 return ret; 35 } 36 }
有人认为用stack是reverse链表了,我认为只要没有reverse input structure就没有问题,因为毕竟元素val和指针next都没有变化。
也有人用比较长度来算的,我自己就不想看了。
还有人认为stack不可以,但是用了recursive方法。区别也不是很大。
更多讨论:
https://discuss.leetcode.com/category/571/add-two-numbers-ii