主要写写编程方面的题目:
我是一面。
1.找链表的中间结点:
思路很简单,双指针,一个走一步,一个走2步。然后走2步的走到末尾,那么走得慢的那个在正中间。
struct node findMiddle(struct node* root)
{
if(!root) return NULL;
struct node* fast,slow;
fast=root;
slow=root;
while(fast)
{
fast=fast->next;
if(!fast->next) break;
fast=fast->next;
slow=slow->next;
}
return slow;
}
2.逆转单链线性表
这里需要定义好变量,不然写起来容易乱套。
定义当前节点为p,其后继结点为q,而其前驱结点为pre。
初始时p置为root,q=p->next,pre置为NULL。
随后,
while(p)
{
q=p->next;
p->next=pre;
pre=p;
p=q;
}
这样逐个往前走,最后,root=pre;
3.求二叉树的深度,兼考察二叉树DFS和BFS。
二叉树的很多编程问题要用递归的角度去考虑比较方便。
递归过程和DFS有些神似。
int depth(btree* root)
{
if(!root) return 0;
int depth1=depth(root->leftChild);
int depth2=depth(root->rightChild);
return (depth1>depth2)?(depth1+1):(depth2+1);
}
广度遍历BFS有些类似。它的核心思想是需要构建一个队列来存放层序遍历的结果。当层序遍历结果为空之后,程序结束:
if (!root) return 0;//当树为空,其深度为0;
btree head=root;
int cnt=1;
int depth=0;
queue q;
q.add(root);
while(q.size())
{
head=q.delete();
cnt--;
if(head->leftChild) q.add(head->leftChild);
if(head->rightChild) q.add(head->rightChild);
if(!cnt)
{
depth++;
cnt=q.size();//refresh size of cnt
}
}
完毕