题目
https://leetcode.com/problems/add-two-numbers/
思路
- 遍历两个列表,逐步加和,直到两个列表都为空
- 增加进位值存储
- 新建一个空值的头节点,方便操作
代码
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// 新增空的头结点,最终返回head.next即可
ListNode head = new ListNode();
ListNode nowNode = head;
// 进位值
int addUp = 0;
while (l1 != null || l2 != null) {
int value = addUp;
if (l1 != null) {
value += l1.val;
l1 = l1.next;
}
if (l2 != null) {
value += l2.val;
l2 = l2.next;
}
addUp = value / 10;
value = value % 10;
nowNode.next= new ListNode(value);
nowNode = nowNode.next;
}
// 最后进位值大于0,需要新增进位值的节点
if (addUp > 0) {
nowNode.next= new ListNode(addUp);
}
return head.next;
}
网友评论