这篇文章主要介绍了php实现合并两个排序链表的方法,涉及php针对链表的遍历、判断、排序等相关操作技巧,需要的朋友可以参考下
本文实例讲述了php实现合并两个排序链表的方法。分享给大家供大家参考,具体如下:
问题
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解决思路
简单的合并排序。由于两个数列本来就是递增的,所以每次将两个数列中较小的部分拿过来就可以了。
实现代码
<?php/*class listnode{ var $val; var $next = null; function __construct($x){ $this->val = $x; }}*/function merge($phead1, $phead2){ if($phead1 == null) return $phead2; if($phead2 == null) return $phead1; $rehead = new listnode(); if($phead1->val < $phead2->val){ $rehead = $phead1; $phead1 = $phead1->next; }else{ $rehead = $phead2; $phead2 = $phead2->next; } $p = $rehead; while($phead1&&$phead2){ if($phead1->val <= $phead2->val){ $p->next = $phead1; $phead1 = $phead1->next; $p = $p->next; } else{ $p->next = $phead2; $phead2 = $phead2->next; $p = $p->next; } } if($phead1 != null){ $p->next = $phead1; } if($phead2 != null) $p->next = $phead2; return $rehead;}
您可能感兴趣的文章:php实现的mongodb单例模式操作类的相关讲解
tp5(thinkphp5)操作mongodb数据库的方法详解
php class soapclient not found解决方法的讲解
以上就是php实现合并两个排序链表的方法讲解的详细内容。