鏈表帶環問題/設計一個類不能被繼承/設計一個類只能在堆(棧)上創建對象

判斷鏈表是否帶環?若帶環求環的長度?若帶環求環的入口點?

class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: The node where the cycle begins. 
     *           if there is no cycle, return null
     */

    //這裏是快慢指針判斷是否帶環
    ListNode* hasCycle(ListNode *head) {
        // write your code here
        ListNode* fast=head,*slow=head;
        while(fast&&fast->next)
        {
            fast=fast->next->next;
            slow=slow->next;
            if(fast==slow)
                return fast;
        }
        return NULL;
    }
    ListNode *detectCycle(ListNode *head) {
        // write your code here
            ListNode* incycle=hasCycle(head);//判斷是否有環,返回環內點
            if(incycle==NULL)
                return NULL;
            ListNode* slow=head;
            while(slow!=incycle)
            {
                incycle=incycle->next;
                slow=slow->next;
            }
            return slow;          
    }
};

這裏就直接貼代碼了,因爲原來寫過一次了。
不懂的話可以點這裏

設計一個類不能被繼承

  • final
    C++11關鍵字final用來聲明一個類,使類不能作爲基類,也就是不能被繼承,或者該類的虛函數不能被派生類重寫(加在虛函數後。)
class A final 
{
public:
    A(){}
    ~A(){};

protected:
    int a;
};

這樣定義類即可

  • 構造函數私有
    派生類構造函數會調用基類構造函數,而基類設置成私有的則派生類不能調用基類構造函數,所以無法繼承。但是這種方法有缺點,例如只能在堆上創建對象,使用不方便等。
class A  
{
public:
    static A* Get()
    {
        return new A;
    }
private:
    A(){}
    ~A(){}
};
  • 友元+模板
template <typename T>
class _A
{
    friend T;

private:
    _A() {}
    ~_A() {}
};

class A : virtual public _A<A>
{
public:
    A() {}
`
~A() {}
};

這裏的class A才做到不能被繼承,並且相近於使用。

設計一個類只能在堆(棧)上創建對象

  • only heap
    因爲要禁止棧上創建對象在棧上創建,很容易想到將構造函數設置爲private,但是如果這樣new動態創建也不能了,那怎麼辦呢,可以將析構函數private,然後再將給外面一個調用析構函數的外部公共接口。
class A{
public:
    A(){}
    void De()
    {
        delete this;
    }
protected:
    ~A(){}
};
  • only stack
    這很簡單,因爲堆上開闢肯定能夠要用到new所以直接將new重載,然後設置爲私有即可,可以只聲明不實現。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章