2021年c++程序员招聘笔试大全详解.docVIP

  • 4
  • 0
  • 约1.84万字
  • 约 37页
  • 2020-11-13 发布于江苏
  • 举报
c/c++ 笔试题及分析目大全 单向链表反转是一个常常被问到一个 面试题,也是一个很基础问题。比如一个链表是这么: 1-2-3-4-5 经过反转后成为5-4-3-2-1。 最轻易想到方法遍历一遍链表,利用一个辅助指针,存放遍历过程中目前指针指向下一个元素,然后将目前节点元素指针反转后,利用已经存放指针往后面继续遍历。源代码以下: 1. struct linka { 2. int data; 3. linka* next; 4. }; 5. void reverse(linka* head) { 6. if(head null) 7. return; 8. linka *pre, *cur, *ne; 9. pre=head; 10. cur=head-next; 11. while(cur) 12. { 13. ne = cur-next; 14. cur-next = pre; 15. pre = cur; 16. cur = ne; 17. } 18. head-next = null; 19. head = pre; 20. } 还有一个利用递归方法。这种方法基础思想是在反转目前节点之前先调用递归函数反转后续节点。源代码以下。不过这个方法有一个缺点,就是在反转后最终一个结点会形成一个环,所以必需将函数返回节点next域置为null。因为要改变head指针,所以我用了引用。算法源代码以下: 1. linka* reverse(linka* p,linka* head) 2. { 3. if(p null || p-next null) 4. { 5. head=p; 6. return p; 7. } 8. else 9. { 10. linka* tmp = reverse(p-next,head); 11. tmp-next = p; 12. return p; 13. } 14. } ②已知string类定义以下: class string { public: string(const char *str = null); // 通用结构函数 string(const string another); // 拷贝结构函数 ~ string(); // 析构函数 string operater =(const string rhs); // 赋值函数 private: char *m_data; // 用于保留字符串 }; 尝试写出类组员函数实现。 答案: string::string(const char *str) { if ( str null ) //strlen在参数为null时会抛异常才会有这步判定 { m_data = new char[1] ; m_data[0] = {content} ; } else { m_data = new char[strlen(str) + 1]; strcpy(m_data,str); } } string::string(const string another) { m_data = new char[strlen(another.m_data) + 1]; strcpy(m_data,other.m_data); } string string::operator =(const string rhs) { if ( this rhs) return *this ; delete []m_data; //删除原来数据,新开一块内存 m_data = new char[strlen(rhs.m_data) + 1]; strcpy(m_data,rhs.m_data); return *this ; } string::~string() { delete []m_data ; } ③网上流传c++笔试题汇总 1.求下面函数返回值(微软) int func(x) { int countx = 0; while(x) { countx ++; x = x(x-1); } return countx; } 假定x = 9999。 答案:8 思绪:将x转化为2进制,看含有1个数。 2. 什么是“引用”?申明和使用“引用”要注意哪些问题? 答:引用就是某个目标变量“别名”(alias),对应用操作和对变量直接操作效果完全相同。申明一个引用时候,切记要对其进行初始化。引用申明完成后,相当于目标变量名有两个名称,即该目标原名称和引用名,不能再把该引用名作为其它变量名别名。申明一个引用,不是新定义了一个变量,它只表示该引用名是目标变量名一部分名,它本身不是一个数据类型,所以引用本身不占存放单元,系统也不给引用分配存放单元。不能建立数组引用。 3. 将“引用”作为函数参数

文档评论(0)

1亿VIP精品文档

相关文档