题解 | #链表相加(二)#

链表相加(二)

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;
}

先翻转两个链表,相加后再把结果翻转。注意翻转函数可以封装

全部评论

相关推荐

不愿透露姓名的神秘牛友
10-04 05:12
kalistar:简历留六个字,北京大学(本科),黑体加粗,看看哪个hr不长眼敢碰瓷我们北大✌
点赞 评论 收藏
分享
10-13 13:49
南京大学 财务
饿魔:笑死我了,你简直是个天才
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务