基本思想:
设置两个指针,都指向链表的头节点。两个指针同时从链表的头节点出发,一个指针每次走一步,另一个指针每次走两步。
1.走得快的指针走到链表末尾时,走得慢的指针刚好指向链表的中间节点。
2.走得快的指针如果追的上走得慢的指针,则链表为环形链表,反之不是。
代码如下:
#include <iostream>
#include <stdexcept>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x):val(x),next(NULL){}
};
bool IsCircleList(ListNode *pHead)
{
ListNode *p1=pHead;
ListNode *p2=pHead;
if(pHead==NULL||pHead->next==NULL) throw runtime_error("List is NULL");
while(p2->next!=NULL&&p2->next->next!=NULL)
{
p1=p1->next;
p2=p2->next->next;
if(p2==p1)
{
return true;
}
}
return false;
}
ListNode *MiddleofList(ListNode *pHead)
{
ListNode *p1=pHead;
ListNode *p2=pHead;
if(pHead==NULL) throw runtime_error("List is NULL");
if(IsCircleList(pHead)) throw runtime_error("List is circle");
while(p2->next!=NULL&&p2->next->next!=NULL)
{
p1=p1->next;
p2=p2->next->next;
}
return p1;
}
int main()
{
ListNode *n1=new ListNode(1);
ListNode *n2=new ListNode(2);
ListNode *n4=new ListNode(4);
ListNode *n5=new ListNode(5);
n1->next=n2;
n2->next=n4;
n4->next=n5;
// n5->next=n1;
ListNode *res=MiddleofList(n1);
cout<<IsCircleList(n1)<<endl;
// cout<<res->val<<endl;
}