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

栏目: PHP · 发布时间: 6年前

内容简介:2019-6-28 星期五 开始吧又到了思考人生的周末了

2019-6-28 星期五 开始吧

又到了思考人生的周末了 Leetcode基础刷题之 <a href='https://www.codercto.com/topics/18749.html'>PHP</a> 解析(21. Merge Two Sorted Lists)

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

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

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

很常规的思路就是每次比较两个链表的头指针的值,谁小谁进入新的链表,然后指针指向它的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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Refactoring

Refactoring

Martin Fowler、Kent Beck、John Brant、William Opdyke、Don Roberts / Addison-Wesley Professional / 1999-7-8 / USD 64.99

Refactoring is about improving the design of existing code. It is the process of changing a software system in such a way that it does not alter the external behavior of the code, yet improves its int......一起来看看 《Refactoring》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器