This article mainly introduces the PHP implementation of two sorted list of the method, involving PHP for the chain list of traversal, judgment, sequencing and other related operations skills, the need for friends can refer to, hope to help everyone.
Problem
Input two monotonically increasing list, output two list of linked lists, of course, we need to synthesize the linked list to meet the monotone non-reduction rules.
Solution Ideas
A simple merge sort. Since two numbers are incremented, each of the smaller parts of the two series can be taken over.
Implementation code
<?php/*class listnode{var $val; var $next = NULL; function __construct ($x) {$th Is->val = $x; }}*/function Merge ($pHead 1, $pHead 2) {if ($pHead 1 = = null) return $pHead 2, if ($pHead 2 = = null) return $pHead 1; $reHead = New ListNode (); if ($pHead 1->val < $pHead 2->val) {$reHead = $pHead 1; $pHead 1 = $pHead 1->next; }else{$reHead = $pHead 2; $pHead 2 = $pHead 2->next; } $p = $reHead; while ($pHead 1&& $pHead 2) {if ($pHead 1->val <= $pHead 2->val) {$p->next = $pHead 1; $pHead 1 = $pHead 1->next; $p = $p->next; } else{$p->next = $pHead 2; $pHead 2 = $pHead 2->next; $p = $p->next; }} if ($pHead 1! = null) {$p->next = $pHead 1;} if ($pHead 2! = null) $p->next = $pHead 2; return $reHead;}