金山云面经2015

主要写写编程方面的题目:


我是一面。

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

  }

}

完毕


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值