1.如何判断一个单链表是有环的?(注意不能用标志位,最多只能用两个额外的指针)
答:判断一个单链表是否有环最简单的做法是定义两个指针,一个指针每次递增一步,另一个指针每次递增两步,如果是有环的,那么两者必然会重合,反之亦然。
代码如下:
bool check(const node* head)
{
if (head == NULL)
{
return false;
}
node* low=head;
node* fast=head;
while ((low->next != NULL) && (fast->next->next != NULL))
{
low = low->next;
fast = fast->next->next;
if (low == fast)
{
return true;
}
}
return false;
}2.斐波那契数列,1、1、2、3、5、8......编写程序求第十项,可用递归?
答:可以用递归的方式。f(n) = f(n-1) + f(n-2);
代码如下:
int Phe(int n)
{
if (n == 1 || n == 2)
{
return 1;
}
return (Phe(n-1)+Phe(n-2));
}3.写一个函数,将一个字符串的\t都转换成4个空格?
答:代码为:
void ReplaceTab(char* strDst,const char* strSrc)
{
assert(strSrc != NULL);
while (*strSrc != '\0')
{
if (*strSrc == '\t')
{
*strDst++ = ' ';
*strDst++ = ' ';
*strDst++ = ' ';
*strDst++ = ' ';
}
else
*strDst++ = *strSrc;
strSrc++;
}
}

被折叠的 条评论
为什么被折叠?



