You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode head = new ListNode(-1); ListNode p = head; int carry = 0; while(l1 != null || l2 != null){ int result = 0; int va = (l1 == null)? 0: l1.val; int vb = (l2 == null)? 0: l2.val; result = (va+vb+carry)%10; carry = (va+vb+carry)/10; p.next = new ListNode(result); p = p.next; l1 = (l1 == null ? null : l1.next); l2 = (l2 == null ? null : l2.next); } if(carry != 0){ p.next = new ListNode(carry); } return head.next; } }
stack 解法,不 reverse list
1 public static ListNode addTwoNumber(ListNode l1, ListNode l2){ 2 Stack<Integer> s1 = new Stack<Integer>(); 3 Stack<Integer> s2 = new Stack<Integer>(); 4 5 ListNode fake = new ListNode(Integer.MIN_VALUE); 6 7 ListNode runner = l1; 8 while(runner != null){ 9 s1.push(runner.val); 10 runner = runner.next; 11 } 12 13 runner = l2; 14 while(runner != null){ 15 s2.push(runner.val); 16 runner = runner.next; 17 } 18 19 runner = fake; 20 int carry = 0; 21 while(!s1.empty() || !s2.empty()){ 22 int v1 = (s1.empty()? 0: s1.pop()); 23 int v2 = (s2.empty()? 0: s2.pop()); 24 int d = v1+v2+carry; 25 carry = d/10; 26 runner.next = new ListNode(d%10); 27 runner =runner.next; 28 } 29 30 if(carry != 0){ 31 runner.next = new ListNode(carry); 32 } 33 34 // reverse the result list 35 ListNode head = fake.next; 36 fake.next = null; 37 ListNode slow = head, fast = head.next, tmp = null; 38 while(fast != null){ 39 tmp = fast.next; 40 fast.next = slow; 41 slow = fast; 42 fast = tmp; 43 } 44 head.next = null; 45 46 47 return slow; 48 } 49