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

来源:互联网 发布:java 异或加密算法 编辑:程序博客网 时间:2024/05/20 16:41

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






阅读全文
0 0
原创粉丝点击