题目描述:判断一个单向链表是否形成环形结构;
思路分析:定义一个快慢指针,快指针一次走两步,慢指针一次走一步,如果链表有环,则一定可以相遇。
代码实现:
#include<iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
bool Insert_tail(Node **list,int value)//尾插
{
Node *node = new Node;
node -> data = value;
node ->next = NULL;
if(*list == NULL)
{
*list = node;
return true;
}
Node *p = *list;
for(;p->next !=NULL;p=p->next );
p->next = node;
return true;
}
Node *FindValue(Node *list,int value)
{
if(list == NULL)
{
return NULL;
}
Node *p = list;
for(;p!=NULL;p=p->next )
{
if(p->data == value)
{
return p;
}
}
return NULL;
}
bool IsRing(Node *list)//是否成环
{
if(list == NULL)
{
return false;
}
Node *fast = list;
Node *last = list;
while(1)
{
fast = fast->next; //fast先走一步
if(fast == NULL)//有空指针,则证明一定不成环形
{
return false;
}
else if(fast == last) //如果快慢指针相遇,则证明有环
{
return true;
}
fast = fast->next ;//fast再走一步
last = last ->next ;//last走一步
}
}
void clear(Node **list)//清除
{
Node *p = *list;
for(;p!=NULL;p=p->next )
{
Node *q = p -> next;
p->next = q->next;
delete q;
}
delete p;
}
void Show(Node *list)//打印函数
{
if(list == NULL)
return;
Node *p = list;
for(;p != NULL;p = p->next)
{
cout<<p->data<<" ";
}
cout<<endl;
}
int main()
{
Node *head1 = NULL;
Node *head2 = NULL;
int arr[] = {1,2,3,4,5};
int lenarr = sizeof(arr)/sizeof(arr[0]);
for(int i=0;i<lenarr;++i)
{
Insert_tail(&head1,arr[i]); //尾插
Insert_tail(&head2,arr[i]); //尾插
}
Show(head1);
Show(head2);
Node *p =FindValue(head1,2);
Node *q = FindValue(head1,5);
q->next = p;
cout<<IsRing(head1)<<endl;
cout<<IsRing(head2)<<endl;
}
总结:快慢指针的思想要掌握哦~