Add Two Numbers
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
这题是说: 给出两个链表, 每个链表代表一个多位整数, 个位在前. 比如2->4->3代表着342. 求这两个链表代表的整数之和(342+465=807), 同样以倒序的链表表示.
难度: Medium
这个题目就是模拟人手算加法的过程, 需要记录进位. 每次把对应位置, 两个节点(如果一个走到头了, 就只算其中一个的值), 加上进位值, 作为结果节点的值, 如果大于9, 需要把进位剥离出来.
public class Solution {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int addUp = 0;
ListNode ret = null;
ListNode cur = null;
while (l1 != null || l2 != null) {
if (cur == null) {
cur = ret = new ListNode(0);
} else {
cur.next = new ListNode(addUp);
cur = cur.next;
}
cur.val += (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val);
addUp = cur.val / 10;
cur.val = cur.val % 10;
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
}
if (addUp > 0) {
cur.next = new ListNode(addUp);
}
return ret;
}
public static void main(String[] args) {
Solution s = new Solution();
ListNode a = s.new ListNode(2);
a.next = s.new ListNode(4);
a.next.next = s.new ListNode(3);
ListNode b = s.new ListNode(5);
b.next = s.new ListNode(6);
// b.next.next = s.new ListNode(4);
ListNode c = s.addTwoNumbers(a, b);
while (true) {
System.out.println(c.val);
if (c.next != null) {
c = c.next;
} else {
break;
}
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。