Home>Article>Backend Development> Detailed explanation of merging two sorted linked lists in PHP

Detailed explanation of merging two sorted linked lists in PHP

小云云
小云云 Original
2018-01-20 09:22:18 1579browse

This article mainly introduces the method of merging two sorted linked lists in PHP, involving PHP's related operating techniques for linked list traversal, judgment, sorting, etc. Friends who need it can refer to it. I hope it can help everyone.

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

Related recommendations:

JavaScript data Structure of singly linked list and circular linked list example sharing

PHP method to get the Kth node from the last in the linked list example sharing

PHP Detailed explanation of double linked list Example

The above is the detailed content of Detailed explanation of merging two sorted linked lists in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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