An explanation of how to merge two sorted linked lists in PHP

jacklove
Release: 2023-04-02 07:30:02
Original
1275 people have browsed it

This article mainly introduces the method of merging two sorted linked lists in PHP, involving PHP's related operating skills of traversing, judging, sorting and other linked lists. Friends in need can refer to the following

The examples in this article are described PHP implements the method of merging two sorted linked lists. Share it with everyone for your reference, the details are as follows:

Question

Input two monotonically increasing linked lists, and output the result of the synthesis of the two linked lists Linked list, of course we need the synthesized 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

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

You may be interested Article:

Related explanation of the mongoDB singleton mode operation class implemented by php

Detailed explanation of the method of operating mongoDB database with tp5 (thinkPHP5)

PHP Class SoapClient not found solution explanation

The above is the detailed content of An explanation of how to merge two sorted linked lists in 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!