Code sharing for merging two sorted linked lists using PHP

php中世界最好的语言
Release: 2023-03-26 22:18:01
Original
1429 people have browsed it

This time I will share with you the code for merging two sorted linked lists in PHP. What are the precautions for merging two sorted linked lists in PHP? The following is a practical case, let's take a look.

Question

Input two monotonically increasing linked lists and output the combined linked list of the two linked lists. Of course, we need the combined linked list to satisfy the monotonic non-decreasing rule.

Solution idea

Simple merge sort. Since the two arrays are inherently increasing, just take the smaller part of the two arrays 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;
}
Copy after login
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

Detailed explanation of steps to develop WeChat remote control server with PHP

imagecopymerge() function steps to create translucent watermark Detailed explanation

The above is the detailed content of Code sharing for merging two sorted linked lists using PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template