代码:
/** * 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 result = null; ListNode temp = null, node = null; int digit = 0, bit = 0; while (l1 != null && l2 != null) { digit = l1.val + l2.val + bit; bit = digit / 10; digit = digit % 10; node = new ListNode(digit); if (result == null) { result = node; temp = result; } else { temp.next = node; temp = temp.next; } l1 = l1.next; l2 = l2.next; } while (l1 != null) { digit = l1.val + bit; bit = digit / 10; digit = digit % 10; node = new ListNode(digit); if (result == null) { result = node; temp = result; } else { temp.next = node; temp = temp.next; } l1 = l1.next; } while (l2 != null) { digit = l2.val + bit; bit = digit / 10; digit = digit % 10; node = new ListNode(digit); if (result == null) { result = node; temp = result; } else { temp.next = node; temp = temp.next; } l2 = l2.next; } if (bit != 0) { node = new ListNode(bit); if (result == null) { result = node; temp = result; } else { temp.next = node; temp = temp.next; } } return result; }}