两数相加

2022-07-14  本文已影响0人  Newzer
<?php

class ListNode {
    public $val = 0;
    public $next = null;
    function __construct($val = 0, $next = null) {
        $this->val = $val;
        $this->next = $next;
    }
}

$head1 = $cur1 = new ListNode(1);

for ($i = 2; $i < 5; $i++) {
    $cur1->next = new ListNode($i);
    $cur1 = $cur1->next;
}

$head2 = $cur2 = new ListNode(3);

for ($i = 4; $i < 9; $i++) {
    $cur2->next = new ListNode($i);
    $cur2 = $cur2->next;
}

print_r(addTwoNumbers($head1,$head2));

function addTwoNumbers($l1, $l2) {
        if ($l1 === null) { return $l2;}
        if ($l2 === null) { return $l1;}

        $flag = 0;
        $l3 = $cur = new ListNode();
        
        while ($l1 || $l2) {
            $a = ($l1->val)?$l1->val:0;
            $b = ($l2->val)?$l2->val:0;
            $sum = $a + $b + $flag;
            
            if ($sum >= 10) {
                $sum = $sum - 10;
                $flag = 1;
            }else {
                $flag = 0;
            }
            $cur->next = new ListNode($sum);
            
            $l1 = $l1->next;
            $l2 = $l2->next;
            $cur = $cur->next;
        }
        if ($flag > 0) {
            $cur->next = new ListNode($flag);
        }
        return $l3->next;
    }
上一篇 下一篇

猜你喜欢

热点阅读