publicclasstwoSum_445{ publicstaticvoidmain(String[] args){ } publicclassListNode{ int val; ListNode next; ListNode(int x) { val = x; } } /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ 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; }
int carry = 0;//进位符号 ListNode head = null; while(!stack1.empty() || !stack2.empty()){ int sum = carry; sum += stack1.isEmpty()? 0:stack1.pop(); sum += stack1.isEmpty()? 0:stack2.pop(); ListNode node = new ListNode(sum % 10); node.next = head; head = node; carry = sum / 10; } return head; }