#include <vector>
using namespace std;
struct ListNode
{
int val;
struct ListNode *next;
ListNode(int x): val(x),next(NULL) {}
};
class CreatList
{
public:
ListNode *Creat(vector<int> A)
{
if(A.empty())
return NULL;
ListNode *head=new ListNode(A[0]),*p=head;
for(vector<int>::iterator iter=A.begin()+1;iter!=A.end();iter++)
{
(*p).next=new ListNode(*iter);
p=(*p).next;
}
return head;
}
ListNode *Creat1(vector<int> A)
{
if(A.empty())
return NULL;
ListNode *head=new ListNode(A[0]),*p=head,*tmp;
int count=0;
for(vector<int>::iterator iter=A.begin()+1;iter!=A.end();iter++)
{
count++;
(*p).next=new ListNode(*iter);
p=(*p).next;
if(count==3)
tmp=p;
}
p->next=tmp;
return head;
}
};
//判断是否为有环链表
bool chkLoop(ListNode* head)
{
if(!head)
return false;
ListNode *slow=head,*fast=head;
while(((*fast).next&&(*(*fast).next).next))
{
slow=(*slow).next;
fast=(*(*fast).next).next;
if(slow==fast)
break;
}
if(!(*fast).next||!(*(*fast).next).next)
return false;
return true;
}
//找到有环链表的入口
ListNode* findLoop(ListNode* head)
{
if(!head)
return NULL;
ListNode *slow=head,*fast=head;
while(((*fast).next&&(*(*fast).next).next))
{
slow=(*slow).next;
fast=(*(*fast).next).next;
if(slow==fast)
break;
}
if(!(*fast).next||!(*(*fast).next).next)
return NULL;
slow=head;
while(slow!=fast)
{
slow=slow->next;
fast=fast->next;
}
return slow;
}
void print(ListNode *head)
{
ListNode *p=head;
while(p)
{
cout<<(*p).val<<" ";
p=(*p).next;
}
cout<<endl;
}
//有环链表打印
void print1(ListNode *head)
{
ListNode *p=head;
ListNode *head_c=findLoop(head);
int count=0;
while(p)
{
if(p==head_c&&(count==1))
break;
if(p==head_c)
count=1;
cout<<(*p).val<<" ";
p=(*p).next;
}
cout<<endl;
}
int main()
{
int a[7] ={1,2,3,4,5,6,7},b[5]={2,4,6,8,10};
vector<int> arr(a,a+7),brr(b,b+5);
CreatList C;
ListNode *head_a=C.Creat(arr);
ListNode *head_b=C.Creat1(brr);
print(head_a);
if(chkLoop(head_b))
cout<<"this is a loop list"<<endl;
print1(head_b);
return 0;
}
6944




被折叠的 条评论
为什么被折叠?



