面试常见基本题目总结及php实现(第三部分:杂七杂八来一套)

1链表反转(不建立数组,用2个传递量来处理)

 

function ReverseList($head){
	$pre=null;
	while($head!=null){
		$next=$head->next;
		$head->next=$pre;
		$pre=$head;
		$head=$next;
	}
	return $pre;
}

链表的一些别的操作,例如

获取链表的倒数第三个节点:

一种方法是采用两个指针,一个先走三步,然后两个在同时往后走,当先走的到达null时,后走的就是倒数第三个了。

另一种方法是只采用一个指针,倒数第三个节点那就是说他的$p->next->next->next为空时,他就是倒数第三个节点了。

 

2二叉树的深度

二叉树其实很好用递归

 

function TreeDepth($pRoot)
{
    // write code here
    if($pRoot==null){return 0;}
    if($pRoot->left==null&&$pRoot->right==null){return 1;}
    $num1=1+TreeDepth($pRoot->left);
    $num2=1+TreeDepth($pRoot->right);
    $num=($num1>$num2)?$num1:$num2;
    return $num;
}

 

3比较两个树是否相同

这个用递归比较本节点和左右节点是否相等

 

function is_equal($root1,$root2){
	if($root1==null&&$root2==null){return true;}
	if($root1!=null&&$root2!=null&&$root1->val==$root2->val){
		if(is_equal($root1->left,$root2->left)){
			if(is_equal($root1->right,$root2->right)){
				return true;
			}
		}
	}
	return false;
}

4二分查找
前提是有序数组查找,比较中间位置的数和查找的数的大小,然后确定在哪个部分

 

有递归和非递归两种,非递归的也不难。

 

<?php
$array=array(1,2,3,4,5,6,7);
print search($array,5);
function search($array,$key){
	$low=0;
	$high=count($array)-1;
	while($low<=$high){
		$mid=floor(($low+$high)/2);
		if($array[$mid]==$key){
			return $mid;
		}
		if($array[$mid]>$key){
			$high=$mid-1;
		}
		if($array[$mid]<$key){
			$low=$mid+1;
		}
	}
	return false;
}

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值