题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
<?php
/*class ListNode{
var $val;
var $next = NULL;
function __construct($x){
$this->val = $x;
}
}*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
function addInList( $head1 , $head2 )
{
if($head1 == null){
return $head2;
}
if($head2 == null){
return $head1;
}
// 翻转两个链表
$reverse1 = reverseList($head1);
$reverse2 = reverseList($head2);
$new = null;
$newHead = null;
$addBit = 0;
while($reverse1 != null || $reverse2 != null){
if($reverse1 != null && $reverse2 != null) {
$bitResult = $reverse1->val + $reverse2->val + $addBit;
}elseif($reverse1 == null && $reverse2 != null){
$bitResult = $reverse2->val + $addBit;
}elseif($reverse1 != null && $reverse2 == null){
$bitResult = $reverse1->val + $addBit;
}
if($bitResult > 9){
$bitResult -= 10;
$addBit = 1;
}else{
$addBit = 0;
}
$temp = new ListNode($bitResult);
if($new == null){
$new = $temp;
$newHead = $temp;
}else{
$new->next = $temp;
$new = $new -> next;
}
$reverse1 = $reverse1 ->next;
$reverse2 = $reverse2 -> next;
}
if($addBit > 0){
$new->next = new ListNode($addBit);
}
return reverseList($newHead);
}
function reverseList($head){
$pre = null;
$beg = $head;
while($beg != null){
$temp = $beg->next;
$beg->next = $pre;
$pre = $beg;
$beg = $temp;
}
return $pre;
}
先翻转两个链表,相加后再把结果翻转。注意翻转函数可以封装

腾讯云智研发成长空间 309人发布