/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ publicclassSolution{ public ListNode addTwoNumbers(ListNode l1, ListNode l2){ ListNode result = null; Stack<ListNode> stack = new Stack<ListNode>(); int flag = 0; while(l1 != null && l2 != null){ int sum = l1.val + l2.val + flag; int val = sum - 10; flag = 0; if(val >= 0){ flag = 1; }else{ val = sum; } ListNode nt = new ListNode(val); stack.push(nt); l1 = l1.next; l2 = l2.next; } while(l1 != null){ int sum = l1.val + flag; int val = sum - 10; flag = 0; if(val >= 0){ flag = 1; }else{ val = sum; } ListNode nt = new ListNode(val); stack.push(nt); l1 = l1.next; } while(l2 != null){ int sum = l2.val + flag; int val = sum - 10; flag = 0; if(val >= 0){ flag = 1; }else{ val = sum; } ListNode nt = new ListNode(val); stack.push(nt); l2 = l2.next; } if(flag > 0){ ListNode nt = new ListNode(1); stack.push(nt); } while(!stack.empty()){ ListNode temp = null; temp = stack.pop(); if(result == null){ temp.next = null; result = temp; }else{ temp.next = result; result = temp; } } return result; } }