Problem:
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:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
Intuition:
这个题目总体思路非常直观。就是模拟小学的笔算来做加法。其中解题时要注意两个list长度不一样的情况(比如两位数+3位数),这种情况下直接在位数较短的那一方(先访问到null的那一方)填0就行了。
还有一个要注意的只是对list中的null如何处理。因为处理的表达式较容易,用?:表达式比if else要更方便。
Solution:
1 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { |