LeetCode 445.两数相加 II
题目:
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
思路:反转链表 + 两数相加 I
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode L1 = reverseList(l1);
ListNode L2 = reverseList(l2);
return reverseList(addTwo(L1, L2));
}
private ListNode addTwo(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode();
ListNode cur = dummy;
int carry = 0; // 进位
while (l1 != null || l2 != null || carry != 0) {
if (l1 != null) carry += l1.val;
if (l2 != null) carry += l2.val;
ListNode mid = new ListNode(carry % 10);
cur.next = mid;
cur = cur.next;
carry /= 10;
if (l1 != null) l1 = l1.next;
if (l2 != null) l2 = l2.next;
}
return dummy.next;
}
private ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode nxt = cur.next;
cur.next = pre;
pre = cur;
cur = nxt;
}
return pre;
}
}
性能:
时间复杂度 o(n)
空间复杂度 o(1)
原文地址:https://blog.csdn.net/qq_57349657/article/details/143841461
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!