Leetcode基础刷题之PHP解析(21. Merge Two Sorted Lists)


 2019-6-28 星期五 开始吧


又到了思考人生的周末了2_05.png?tp=webp&wxfrom=5&wx_lazy=1&wx_co=1


Leetcode基础刷题之PHP解析(19. Remove Nth Node From End of List)

cd6fcbe7f9b394d7d8c26ea359c2a685.png



给定两个单链表,让我们从小到大把两个单链表合并成一个链表。



很常规的思路就是每次比较两个链表的头指针的值,谁小谁进入新的链表,然后指针指向它的next位置。好像不用新建链表?每次对比一下它两的大小,假设我们最终返回的链表当前的头指针的值大于另一个链表头指针的值,那么就互换他两,这样就确保了每次返回链表的顺序都是有序的。实现的时候用递归即可。

  /**
     * @param ListNode $l1
     * @param ListNode $l2
     * @return ListNode
     */
    function mergeTwoLists($l1, $l2) {

        if($l1 !==null && $l2 !==null){
            if($l1->val > $l2->val){
                $temp=$l1;
                $l1=$l2;
                $l2=$temp;
            }
            $l1->next=$this->mergeTwoLists($l1->next,$l2);
           
        }
         return $l1??$l2;
    }

换一种思路

  /**
     * @param ListNode $l1
     * @param ListNode $l2
     * @return ListNode
     */
    function mergeTwoLists($l1, $l2) {
        if($l1 ==null) return $l2;
        if($l2 ==null) return $l1;
        
        if($l1->val < $l2->val){
            $l1->next=$this->mergeTwoLists($l1->next,$l2);
            return $l1;
        }else{
            $l2->next=$this->mergeTwoLists($l2->next,$l1);
            return $l2;
        }
    }

Github整理地址:https://github.com/wuqinqiang/leetcode-php


点赞 取消点赞 收藏 取消收藏

<< 上一篇: Leetcode基础刷题之PHP解析(19. Remove Nth Node From End of List)

>> 下一篇: Leetcode PHP题解--D95 108. Convert Sorted Array to Binary Search Tree