您的位置:首页 > 编程语言 > C语言/C++

C++面试题之编程实现

2013-03-19 07:57 281 查看
1)给你个数组1……n进行排序,时间复杂度为O(n),空间复杂度是O(1),

#include<iostream.h>

int main()

{

int a[] = {10,6,9,5,2,8,4,7,1,3};

int len = sizeof(a) / sizeof(int);

int temp;

for(int i = 0; i < len; )

{

temp = a[a[i] - 1];

a[a[i] - 1] = a[i];

a[i] = temp;

if ( a[i] == i + 1)

i++;

}

for (int j = 0; j < len; j++)

cout<<a[j]<<",";

return 0;
}

2)写一个函数,完成内存之间的拷贝。[考虑问题是否全面]   

   char*    mymemcpy(void *dest,void *src,  size_t  count)   

   {   
   assert((dest!=NULL)&&(src!=NULL));

   byte *pdest=(byte*)dest; //防止地址被改变
   byte *psrc=(byte*)src;

  

           if(    pdest>psrc    &&    pdest<psrc+cout    )//需要考虑下超过了长度就会将源地址数据被覆盖

           {   

                   for(    size_t    i=count-1;    i!=-1;    --i    )   

                                   pdest[i]    =    psrc[i];   

           }   

           else   

           {   

                   for(    size_t    i=0;    i<count;    ++i    )   

                           pdest[i]    =    psrc[i];   

           }   

           return    dest;   

   }   

3)编写strcat函数

 已知strcat函数的原型是char *strcat (char *strDest, const char *strSrc);    其中strDest 是目的字符串,strSrc是源字符串。不调用C++/C 的字符串库函数,请编写函数strcat 

char * __cdecl strcat (char * dst, const char * src)

{    

char * cp = dst;

while( *cp )

cp++; /* find end of dst */cp++; /

while( *cp++ = *src++ ) ; /* Copy src to end of dst */

return( dst ); /* return dst */return( dst );



strcat能把strSrc的内容连接到strDest,为什么还要char * 类型的返回值?

答:方便赋值给其他变量

二分查找的代码.:

int binary_search(int* arr, int key, int n)

{

   int low = 0;

   int high = n - 1;

   int mid;

   while (low <= high)

   {

      mid = (high + low) / 2;

      if (arr[mid] > k)

         high = mid - 1;

      else if (arr[mid] < k)

         low = mid + 1;

      else

         return mid;

   }

   return -1;

}

链表的倒序

void Reverse(node *H)

{node *p,*q;

p = H->next;

H->next = NULL;

while(p)

{q = p;p = p->next;q->next = H->next;H->next = p;}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息