You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example:
public ListNode (ListNode p, ListNode q){ ListNode result = new ListNode(0); int big = 0 ; ListNode cur = result; while(p != null || q != null){ int a = p == null ? 0 : p.val; int b = q == null ? 0 : q.val; int val = a + b + big; if (val >= 10){ val -= 10; big = 1; } else { big = 0; } ListNode cld = new ListNode(val); cur.next = cld; cur = cur.next; if (p != null){ p = p.next; } if (q != null){ q = q.next; } } if (big > 0) { cur.next = new ListNode(big); } return result.next; }
近期评论