实现思路:
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
题目分析
假如List1中的头节点是小于List2中的,那么新的链表的头节点必将是List1的头节点,
同理对List2也一样,那么在比较完头节点之后,再将List1中的下一个节点再与List2中的头节点比较,
同样谁小谁进入新链表,然后再比较,直到两个链表比较完,故可用非递归或递归两种方式来做。
代码如下:
<?php
class Node{public $next=null;
public $data;
public function __construct($data=''){
$this->data=$data;
}
}
//新增
function addNode($head,$data){
$cur=$head;
while($cur->next!=null){
$cur=$cur->next;
}
$node=new Node($data);
$cur->next=$node;
}
/**
*
*非递归方式合并两个递增的单链表。
*/
function combineNodeRecrusion($first,$two){
if($first==null){
return $two;
}
if($two==null){
return $first;
}
$root=new Node();
if($first->data<=$two->data){
$root=$first;
$first=$first->next;
}else{
$root=$two;
$tow=$tow->next;
}
$current=$root;
while($first!=null && $two !=null){
if($first->data<= $two->data){
$current->next=$first;
$first=$first->next;
$current=$current->next;
}else{
$current->next=$two;
$two=$two->next;
$current=$current->next;
}
}
if($first!=null){
$current->next=$first;
}
if($two!=null){
$current->next=$two;
}
return $root->next;
}
/***
* 递归合并两个递增的链表
*/
function combineNode($first,$two){
if($first==null){
return $two;
}
if($two==null){
return $first;
}
$three=new Node();
if($first->data<= $two->data){
$three=$first;
$three->next=combineNode($first->next,$two);
}else{
$three=$two;
$three->next=combineNode($first,$two->next);
}
return $three;
}
//遍历
function showNode($head){
$cur=$head;
while($cur->next!=null){
$cur=$cur->next;
echo $cur->data.PHP_EOL;
}
}
//feidigui非递归
function reversNode($head){
if($head==null){
return false;
}
$new=null;
$cur=$head;
while($cur!=null){
$temp=$cur->next;
$cur->next=$new;
$new=$cur;
$cur=$temp;
}
return $new;
}
//递归方式实现
function reversRecursionNode($head){
if($head->next==null){
return $head ;
}
$phead=reversRecursionNode($head->next);
$head->next->next=$head;
$head->next=null;
return $phead;
}
function test(){
$head1=new Node();
addNode($head1,1);
addNode($head1,3);
addNode($head1,5);
addNode($head1,7);
showNode($head1);
echo '--------------';
$head2=new Node();
addNode($head2,2);
addNode($head2,4);
addNode($head2,6);
addNode($head2,8);
showNode($head2);
echo '--------------';
//showNode(combineNode($head1,$head2));
// echo '--------------';
showNode(combineNodeRecrusion($head1,$head2));
}
test();
?>