PHP implements the method of merging two sort linked lists, and php implements Merge Sorting.

Source: Internet
Author: User

PHP implements the method of merging two sort linked lists, and php implements Merge Sorting.

This example describes how to merge two sort linked lists in PHP. We will share this with you for your reference. The details are as follows:

Problem

Input two monotonically incrementing linked lists and output the merged linked lists. Of course, the merged linked lists meet the monotonous rules.

Solution

Simple Merge Sorting. Since the two series are incremental, you can take the smaller part of the two series 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;}

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.