php版两链表对应相加

题目

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
这里学习了来自网络leetcode里面的算法题

//php演示链表需要定义node节点
class listNode 
{
	public $val = 0;
	public $next = null;
	function __construct ($val) {
		$this->val = $val;
	}
}

class solution 
{
	function addTwoNumbers ($l1, $l2) {
		$add = 0;
		$list = new listNode(0);
		$cur = $list;
		while ($l1 || $l2) {
			$x = $l1 != null ? $l1->val : 0;
			$y = $l2 != null ? $l2->val : 0;
			$val = ($x + $y + $add)%10;
			$add = ($x + $y + $add)/10;
			$new = new listNode($val);
			$cur->next = $new;
			$cur = $cur->next;
			if ($l1 != null) {
				$l1 = $l1->next;
			}
			if ($l2 != null) {
				$l2 = $l2->next;
			}	
		}
		if ($add > 0) {
		    $cur->next = new listNode($add);
		}
		return $list->next;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值