Method of Merging Two Sorting Linked Lists by PHP

  • 2021-08-31 07:32:46
  • OfStack

In this paper, an example is given to describe the method of merging two sorted linked lists in PHP. Share it for your reference, as follows:

Problem

Input two monotone incremental linked list, output two linked list after the combination of linked list, of course, we need the combination of linked list to meet the monotone unabated rule.

Solutions

Simple merge sort. Since the two sequences are incremental, it is OK to take the smaller part of the two sequences at a 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;
}

For more readers interested in PHP related contents, please check the topics of this site: "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "php String (string) Usage Summary", "PHP Array (Array) Operation Skills Complete Book", "PHP Common Traversal Algorithms and Skills Summary" and "PHP Mathematical Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: