链表反转

本文详细介绍了单向链表的两种反转方法,并提供了完整的代码示例。此外,还深入探讨了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的个数。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值