当前位置:七七学习网文档大全求职指南求职笔试面试笔试题目C/C++笔试题目常见题目» 正文

C/C++笔试题目常见题目

[10-10 21:21:19]   来源:http://www.77xue.com  笔试题目   阅读:8150
概要:单向链表的反转是一个经常被问到的一个面试题,也是一个非常基础的问题。比如一个链表是这样的:1->2->3->4->5 通过反转后成为5->4->3->2->1。最容易想到的方法遍历一遍链表,利用一个辅助指针,存储遍历过程中当前指针指向的下一个元素,然后将当前节点元素的指针反转后,利用已经存储的指针往后面继续遍历。源代码如下: struct linka { int data; linka* next; }; void reverse(linka*& head) { if(head ==NULL) return; linka *pre, *cur, *ne; pre=head; cur=head->next; while(cur) { ne = cur->next; cur-&
C/C++笔试题目常见题目,标签:驾照笔试题目,腾讯笔试题目,http://www.77xue.com


单向链表的反转是一个经常被问到的一个面试题,也是一个非常基础的问题。比如一个链表是这样的:

1->2->3->4->5
通过反转后成为5->4->3->2->1。
最容易想到的方法遍历一遍链表,利用一个辅助指针,存储遍历过程中当前指针指向的下一个元素,然

后将当前节点元素的指针反转后,利用已经存储的指针往后面继续遍历。源代码如下:
    struct linka {
    int data;
    linka* next;
    };
    void reverse(linka*& head) {
    if(head ==NULL)
                      return;
    linka *pre, *cur, *ne;
    pre=head;
    cur=head->next;
    while(cur)
    {
       ne = cur->next;
       cur->next = pre;
       pre = cur;
       cur = ne;
    }
    head->next = NULL;
    head = pre;
    }
还有一种利用递归的方法。这种方法的基本思想是在反转当前节点之前先调用递归函数反转后续节点。

源代码如下。不过这个方法有一个缺点,就是在反转后的最后一个结点会形成一个环,所以必须将函数的

返回的节点的next域置为NULL。因为要改变head指针,所以我用了引用。算法的源代码如下:
    linka* reverse(linka* p,linka*& head)
    {
    if(p == NULL || p->next == NULL)
    {
       head=p;
       return p;
    }
    else
    {
       linka* tmp = reverse(p->next,head);
       tmp->next = p;
       return p;
    }
    }
②已知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] = '\0' ;
}
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 ;

[1] [2] [3] [4] [5] [6]  下一页


Tag:笔试题目驾照笔试题目,腾讯笔试题目求职指南 - 求职笔试面试 - 笔试题目
联系我们 | 网站地图 | 范文大全 | 管理知识 | 教学教育 | 作文大全 | 语句好词
Copyright http://www.77xue.com--(七七学习网) All Right Reserved.
1 2 3 4 5 6 7 8 9 10