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

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

内容简介: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


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

查看所有标签

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

Numerical Methods and Methods of Approximation in Science and En

Numerical Methods and Methods of Approximation in Science and En

Karan Surana / CRC Press / 2018-10-31

ABOUT THIS BOOK Numerical Methods and Methods of Approximation in Science and Engineering prepares students and other readers for advanced studies involving applied numerical and computational anal......一起来看看 《Numerical Methods and Methods of Approximation in Science and En》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

URL 编码/解码
URL 编码/解码

URL 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具