题目链接:https://leetcode-cn.com/problems/add-two-numbers-ii/submissions/
解题思路:
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 class Solution { 10 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 11 Stack<Integer> l1Stack = buildStack(l1); 12 Stack<Integer> l2Stack = buildStack(l2); 13 ListNode head = new ListNode(-1); 14 ListNode p =head; 15 int carry = 0; 16 int x; 17 int y; 18 while (!l1Stack.isEmpty() || !l2Stack.isEmpty() || carry != 0) { 19 if(!l1Stack.isEmpty()) 20 x = l1Stack.pop(); 21 else 22 x=0; 23 if(!l2Stack.isEmpty()) 24 y = l2Stack.pop(); 25 else 26 y=0; 27 int sum = x + y + carry; 28 ListNode node = new ListNode(sum % 10); 29 node.next = head.next; 30 head.next=node; 31 carry = sum / 10; 32 } 33 return head.next; 34 } 35 36 private Stack<Integer> buildStack(ListNode l) { 37 Stack<Integer> stack = new Stack<>(); 38 while (l != null) { 39 stack.push(l.val); 40 l = l.next; 41 } 42 return stack; 43 } 44 }