判断链表是否带环?若带环求环的长度?若带环求环的入口点?
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重载,然后设置为私有即可,可以只声明不实现。