题目描述:
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
分类: 简单题
1A:False
坑点:当两个链表都走到了尽头,千万不要认为程序就此终止啊。如果借位不为零,还得为下一个节点赋值。我就是因为这个问题被一个这样的输入打回的:(A1失败...
Input [5], [5]
Output [0]
Expect [0, 1]
程序:
/**
* 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 head = result;
int v1 = 0, v2 = 0, v3 = 0, overflow = 0;
while(l1 != null || l2 != null || overflow != 0) {
v1 = v2 = 0;
if (l1 != null) v1 = l1.val;
if (l2 != null) v2 = l2.val;
v3 = v1 + v2 + overflow;
overflow = 0; //reset overflow
if (v3 >= 10) {
v3 -= 10;
overflow = 1;
}
if (head == null) {
head = new ListNode(v3);
result = head;
} else {
head.next = new ListNode(v3);
head = head.next;
}
if (l1 != null) l1 = l1.next;
if (l2 != null) l2 = l2.next;
}
return result;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。