【LeetCode445】两数相加 II

1. 题目

【题目链接】👉两数相加 II

给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

进阶:

如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。

示例:

输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7

2. 解法一:反转相加后再反转

【递归反转链表】

在这里插入图片描述

【非递归反转链表】

在这里插入图片描述


Solution

说明和理解

dummy是新链表的头结点

ListNode dummy = new ListNode(0);

temp指向dummy节点,temp中存放的是dummy节点的地址

ListNode temp = dummy; //temp相当于dummy的指针域

连接,让temp当前指向的节点 指向新计算出的ListNode节点

temp.next = new ListNode(sum%10);

temp指向最新的节点(temp起到链接节点的作用)

temp = temp.next;

在这里插入图片描述

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode h1 = reverse(l1);
        ListNode h2 = reverse(l2);
        //进位的数
        int carry = 0;
        //新链表的头结点
        ListNode dummy = new ListNode(0); 
        //链表节点指针域
        ListNode temp = dummy;
        while(h1 != null || h2 != null || carry != 0) {
            int val1 = h1 == null ? 0 : h1.val;
            int val2 = h2 == null ? 0 : h2.val;
            int sum = val1 + val2 + carry;
            temp.next = new ListNode(sum % 10);
            temp = temp.next;
            carry = sum / 10;
            if(h1 != null)  h1 = h1.next;
            if(h2 != null)  h2 = h2.next;
        } 
        ListNode res = reverse(dummy.next);
        return res;
    }

    public ListNode reverse(ListNode head) {
        if (head == null) return null;
        ListNode prev = null;
        while (head != null) {
            ListNode next = head.next;
            head.next = prev;
            prev = head;
            head = next;
        }
        return prev;
    }
}

3. 解法二:入栈头插法

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stack<Integer> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();
        while(l1 != null) {
            stack1.push(l1.val);
            l1 = l1.next;
        }
        while(l2 != null) {
            stack2.push(l2.val);
            l2 = l2.next;
        }
        int carry = 0;
        ListNode head = null;
        while(!stack1.isEmpty() || !stack2.isEmpty() || carry!= 0) {
            int val1 = stack1.isEmpty() ? 0 : stack1.pop();
            int val2 = stack2.isEmpty() ? 0 : stack2.pop();
            int sum = val1 + val2 + carry;
            ListNode node = new ListNode(sum % 10);
            //头插法
            node.next = head; //节点相连
            head = node;  //移动指向,让最新的节点成为头结点
            carry = sum / 10;
        }
        return head;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章