Leetcode——2. 兩數相加

難度: 中等php

題目

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.html

You may assume the two numbers do not contain any leading zero, except the number 0 itself.node

給出兩個 非空 的鏈表用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式存儲的,而且它們的每一個節點只能存儲 一位 數字。
若是,咱們將這兩個數相加起來,則會返回一個新的鏈表來表示它們的和。
您能夠假設除了數字 0 以外,這兩個數都不會以 0 開頭。git

示例:this

輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
緣由:342 + 465 = 807spa

PHP

這個題目至關因而兩個鏈表進行相加,把鏈表每一節點的值存到新鏈表對應的節點,涉及到進位。3d

/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val) { $this->val = $val; }
 * }
 */
class Solution {

    /**
     * @param ListNode $l1
     * @param ListNode $l2
     * @return ListNode
     */
    function addTwoNumbers($l1, $l2) {
        $add_flag = 0;
        $result_list = new ListNode(0);
        $curr =  $result_list; //指向當前鏈表
        
        do {
            $val = $l1->val + $l2->val + $add_flag;
            if ($val >= 10) {
                $add_flag = 1;
                $val -= 10; //減去,由於進位了
            } else {
                $add_flag = 0;
            }
            
            $tmp_list = new ListNode($val);
            $curr->next = $tmp_list;
            $curr = $curr->next;
            
            $l1 = $l1->next;
            $l2 = $l2->next;
        } while ($l1 || $l2 || $add_flag);

        return $result_list->next;
    }
}

運行結果: code

PHP鏈表打印出來的結構:htm

ListNode Object
(
    [val] => 0
    [next] => ListNode Object
        (
            [val] => 7
            [next] => ListNode Object
                (
                    [val] => 0
                    [next] => ListNode Object
                        (
                            [val] => 8
                            [next] => 
                        )

                )

        )

)

來源

連接:https://leetcode-cn.com/problems/add-two-numbers/blog

參考

一、PHP 鏈表的使用 - 簡書
https://www.jianshu.com/p/e409ec512caa 二、2. Add Two Numbers · leetcode https://leetcode.wang/leetCode-2-Add-Two-Numbers.html

相關文章
相關標籤/搜索