PHP implementation merge two sorted list code share

Source: Internet
Author: User
This time to bring you a PHP implementation combined with two sorted list code sharing, PHP implementation of the merger of two sorting list of considerations, the following is the actual case, together to see.

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;}

Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!

Recommended reading:

PHP Development Remote control server steps in detail

Imagecopymerge () function Create translucent watermark step

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.