这个比较简单,掌握好循环条件以及进位条件。
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode p = l1;
ListNode q = l2;
int ret = 0;
ListNode prev = null;
ListNode head = null;
while(p != null || q != null) {
int x = ret;
if (p != null) {
x = x + p.val;
p = p.next;
}
if (q != null) {
x = x + q.val;
q = q.next;
}
if (x >= 10) {
x = x - 10;
ret = 1;
} else {
ret = 0;
}
ListNode newNode = new ListNode(x);
newNode.next = null;
if (prev == null) {
prev = newNode;
head = newNode;
} else {
prev.next = newNode;
prev = newNode;
}
}
if (ret > 0) {
ListNode newNode = new ListNode(ret);
newNode.next = null;
prev.next = newNode;
prev = newNode;
}
return head;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。