1. 如何实现一个高效的单向链表逆序输出?
参考答案:
下面是其中一种写法,也可以有不同的写法,比如递归等。供参考。
typedefstructnode
{
intdata;
structnode*next;
node(intd):data(d),next(NULL){} }node;
voidreverse(node*head)
{
if(NULL==head||NULL==head->next) {
return;
}
node*prev=NULL; node*pcur=head->next; node*next; while(pcur!=NULL)
{
if(pcur->next==NULL) {
pcur->next=prev;
break;
}
next=pcur->next; pcur->next=prev; prev=pcur;
pcur=next;
}
head->next=pcur; node*tmp=head->next; while(tmp!=NULL)
{ cout<<tmp->data<<"\t"; tmp=tmp->next;
}
}
2. 已知 sqrt (2)约等于 1.414,要求不用 数学库,求 sqrt (2)精确到小数点后 10 位。
考察点
- 基础算法的灵活应用能力(二分法学过数据结构的同学都知道, 但不一定往这个方向考虑;如果学过数值计算的同学,应该还要 能想到牛顿迭代法并解释清楚)
- 退出条件设计
参考答案
- 已知 sqrt(2)约等于 1.414,那么就可以在(1.4, 1.5)区间做二分 查找,如:
a) high=>1.5
b) low=>1.4
c) mid => (high+low)/2=1.45
d) 1.45*1.45>2 ? high=>1.45 : low => 1.45
e) 循环到 c) - 退出条件
a) 前后两次的差值的绝对值<=0.0000000001, 则可退出
8
◼ 代码示例:
const double EPSINON = 0.0000000001;
double sqrt2( ) {
double low = 1.4, high = 1.5; double mid = (low + high) / 2;
while (high – low > EPSINON) {
if (mid*mid < 2) {
high = mid; }
else
{
low = mid; }
mid = (high + low) / 2; }
return mid; }
——摘自阿里巴巴出题专家:江岚/阿里巴巴数据技术高级技术专家
定期更新加关注获取更多免费资源