PHP implements the method of merging two sort linked lists, and php implements Merge Sorting.
This example describes how to merge two sort linked lists in PHP. We will share this with you for your reference. The details are as follows:
Problem
Input two monotonically incrementing linked lists and output the merged linked lists. Of course, the merged linked lists meet the monotonous rules.
Solution
Simple Merge Sorting. Since the two series are incremental, you can take the smaller part of the two series each time.
Implementation Code
<?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;}