给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
https://leetcode.cn/problems/add-two-numbers-ii/description/
class Solution {
public ListNode reversal(ListNode head) {
ListNode newHead = null;
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = newHead;
newHead = cur;
cur = next;
}
return newHead;
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode ans = new ListNode();
ListNode head = new ListNode();
head = ans;
ListNode rev_l1 = reversal(l1);
ListNode rev_l2 = reversal(l2);
int sum = 0;
int carry = 0;
while (rev_l1 != null || rev_l2 != null || carry != 0) {
if (rev_l1 != null) {
sum = sum + rev_l1.val;
}
if (rev_l2 != null) {
sum = sum + rev_l2.val;
}
ListNode cur = new ListNode();
if (sum + carry >= 10) {
cur.val = (sum + carry) - 10;
carry = 1;
sum = 0;
} else {
cur.val = sum + carry;
carry = 0;
sum = 0;
}
ans.next = cur;
ans = ans.next;
if (rev_l1 != null) {
rev_l1 = rev_l1.next;
}
if (rev_l2 != null) {
rev_l2 = rev_l2.next;
}
}
return reversal(head.next);
}
}
解题思路:
首先将两个链表进行反转,这边使用的是头插法,反转后,那么链表的第一个元素就是以个位开始,两个链表就可以直接相加了,如果不反转的话,还要考虑每一位是十位还是百位等等,然后遍历两个链表,从个位开始相加,因为只有两个链表,所以每次相加的进位要么为0,要么为1,不需要担心进位后还需要在进位的情况,通过两个变量sum和array代表相加和和是否进位的标志,然后将每次的计算结果放入到新链表中即可,最后在对结果链表进行反转。
更多LeetCode刷题:https://github.com/xu-zhi-heng/LeetCode_Question