兩數(shù)相加

問題鏈接:
https://leetcode-cn.com/explore/interview/card/top-interview-questions-medium/31/linked-list/82/

給定兩個(gè)非空鏈表來表示兩個(gè)非負(fù)整數(shù)。位數(shù)按照逆序方式存儲(chǔ),它們的每個(gè)節(jié)點(diǎn)只存儲(chǔ)單個(gè)數(shù)字。將兩數(shù)相加返回一個(gè)新的鏈表。
你可以假設(shè)除了數(shù)字 0 之外,這兩個(gè)數(shù)字都不會(huì)以零開頭。

示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807

解題思路:
1、先new一個(gè)ListNode作為head
2、遍歷兩個(gè)鏈表,兩兩相加并記錄進(jìn)位
3、遍歷剩余未遍歷完的鏈表,并使用進(jìn)位相加
4、最后若進(jìn)位為1,增加一個(gè)節(jié)點(diǎn)值為進(jìn)位值
5、head往后移一位

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int upper = 0;
        ListNode p1 = l1;
        ListNode p2 = l2;
        ListNode head = new ListNode(0);
        ListNode p = head;
        while (p1 != null && p2 != null) {
            int sum = p1.val + p2.val + upper;
            if (sum >= 10) {
                sum = sum - 10;
                upper = 1;
            } else {
                upper = 0;
            }
            
            p.next = new ListNode(sum);
            p = p.next;
            
            p1 = p1.next;
            p2 = p2.next;
        }
        
        ListNode nextP = p1 != null ? p1: p2;
        while (nextP != null) {
            int sum = nextP.val + upper;

            if (sum >= 10) {
                sum = sum - 10;
                upper = 1;
            } else {
                upper = 0;
            }
            
            p.next = new ListNode(sum);
            p = p.next;
            nextP = nextP.next;
        }
        
        if (upper > 0) {
            p.next = new ListNode(upper);
            p = p.next;
        }
        
        head = head.next;
        
        return head;
    }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容