【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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章