Home>Article>Backend Development> How to merge two ordered linked lists into one ordered linked list in PHP (code)
The content of this article is about how PHP merges two ordered linked lists into one ordered linked list (code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. helped.
Merge two ordered linked lists into one ordered linked list:
Similar to the part of merging two arrays in merge sort
1. Traverse linked list 1 and linked list 2, compare linked lists 1 and 2 The size of the elements in
2. If the node of linked list 1 is larger than the node of linked list 2, the node will be put into the third-party linked list
3. Go one step down in linked list 1, and vice versa
4. When After one of the two linked lists ends, the other linked list can be put into the third-party linked list
list3 while list1!=null list2!=null if list1->data >= list2->data list3->next=list1 list3=list1 //当前指针后移 list1=list1->next //链表1走一步 else list3->next=list2 list3=list2 list2=list2->next if list1!=null list3->next=list1 if list2!=null list3->next=list2
$linkList=new Node(); $linkList->next=null; $temp=$linkList; for($i=1;$ib580f73c1fdf858295adebea0075fd9edata=$i; $node->next=null; $temp->next=$node; $temp=$node; } //第二个有序的链表 $list2=new Node(); $temp=$list2; for($i=2;$ib580f73c1fdf858295adebea0075fd9edata=$i; $node->next=null; $temp->next=$node; $temp=$node; } //合并两个链表 $newlist=new Node(); $list1=$linkList->next;//跳过头结点 $list2=$list2->next; $list3=$newlist;//一定要赋予给这个临时结点,否则新结点前移的时候就会被覆盖 while($list1!=null && $list2!=null){ if($list1->data49a1a520f602fecfb8aab14707e6054fdata){ $list3->next=$list1;//新链表指向链表1结点 $list3=$list1;//新链表当前结点往前移动 $list1=$list1->next;//链表1往前移动 }else{ $list3->next=$list2; $list3=$list2; $list2=$list2->next; } } if($list1!=null){ $list3->next=$list1; } if($list2!=null){ $list3->next=$list2; } var_dump($newlist);
Related recommendations:
PHP implementation of merging two sorted linked lists code sharing
Detailed explanation of merging two sorted linked lists in PHP
The above is the detailed content of How to merge two ordered linked lists into one ordered linked list in PHP (code). For more information, please follow other related articles on the PHP Chinese website!