PHP implementation merge Two sorted list of methods explained

Source: Internet
Author: User
Tags php class
This article mainly introduces the implementation of PHP to merge two sorted list of methods, involving PHP for the chain list traversal, judgment, sorting and other related operations skills, the need for friends can refer to the next

In this paper, we describe the method of merging two sorted lists with PHP implementation. Share to everyone for your reference, as follows:

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) {  $this->val = $x;}} */function Merge ($pHead 1, $pHead 2) {if ($pHead 1 = = null)  return $pHead 2, if ($pHead 2 = = null)  return $pHead 1; $reHe AD = 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;}

Articles you may be interested in:

PHP implementation of the MongoDB Singleton mode operation of the relevant explanation

TP5 (thinkPHP5) How to manipulate MongoDB database

PHP Class soapclient Not found explanation of workaround

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.