Leetcode PHP题解--D121 21. Merge Two Sorted Lists
码农天地 -D121 21. Merge Two Sorted Lists题目链接
21. Merge Two Sorted Lists
题目分析合并两个有序链表。
思路逐个遍历两个链表,把小的数字塞入数组里。之后再拼起来。
最终代码<?php
/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val) { $this->val = $val; }
* }
*/
class Solution{
private $vals = [];
function mergeTwoLists($l1, $l2) {
$this->iterate($l1, $l2);
$root = $node = NULL;
if($this->vals){
$root = $node = new ListNode(array_pop($this->vals));
}
while(!empty($this->vals)){
$node->next = new ListNode(array_pop($this->vals));
$node = $node->next;
}
return $root;
}
function iterate($l1, $l2){
if(!is_null($l1) && !is_null($l2)){
if($l1->val<=$l2->val){
array_unshift($this->vals, $l1->val);
$l1 = $l1->next;
}
else{
array_unshift($this->vals, $l2->val);
$l2 = $l2->next;
}
}
else if(!is_null($l1)){
array_unshift($this->vals,$l1->val);
$l1 = $l1->next;
}
else if(!is_null($l2)){
array_unshift($this->vals,$l2->val);
$l2 = $l2->next;
}
else if (is_null($l1) && is_null($l2)){
return;
}
$this->iterate($l1, $l2);
}
}
若觉得本文章对你有用,欢迎用爱发电资助。
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。
php介绍
PHP即“超文本预处理器”,是一种通用开源脚本语言。PHP是在服务器端执行的脚本语言,与C语言类似,是常用的网站编程语言。PHP独特的语法混合了C、Java、Perl以及 PHP 自创的语法。利于学习,使用广泛,主要适用于Web开发领域。