写一段代码判断一个单向链表中是否有环
2012-08-05 10:41
337 查看
#include <iostream>
#include <map>
using namespace std;
struct node
{
int data;
struct node *next;
}*linklist,*s,*head;
map<node*,int>m;
bool IsLoop(node *head)
{
node *pSlow=head;
node *pFast=head;
while(pSlow!=NULL && pFast!=NULL)
{
pSlow=pSlow->next;
pFast=pFast->next->next;
if(pSlow==pFast)
return true;
}
return false;
}
node* InsertNode(node *head,int value)
{
if(head==NULL)
{
head=(node *)malloc(sizeof(node));
if(head==NULL)
printf("malloc failed");
else
{
head->data=value;
head->next=NULL;
}
}
else
{
node *temp=(node *)malloc(sizeof(node));
if(temp==NULL)
printf("malloc failed");
else
{
temp->data=value;
temp->next=head;
head=temp;
}
}
return head;
}
int main(void)
{
node *t,*q,*p=NULL;
p=InsertNode(p,8);
p=InsertNode(p,7);
p=InsertNode(p,6);
p=InsertNode(p,5);
p=InsertNode(p,4);
q=p;
p=InsertNode(p,3);
p=InsertNode(p,2);
p=InsertNode(p,1);
t=p;
while(t->next) // 找到链表的尾指针
t=t->next;
t->next=q; // 将链表的尾指针指向第四个节点,这样就构成了一个环
bool flag=IsLoop(p);
if(flag)
cout<<"这个链表存在一个环"<<endl;
else
cout<<"这个链表不存在一个环"<<endl;
system("pause");
return 0;
}
#include <map>
using namespace std;
struct node
{
int data;
struct node *next;
}*linklist,*s,*head;
map<node*,int>m;
bool IsLoop(node *head)
{
node *pSlow=head;
node *pFast=head;
while(pSlow!=NULL && pFast!=NULL)
{
pSlow=pSlow->next;
pFast=pFast->next->next;
if(pSlow==pFast)
return true;
}
return false;
}
node* InsertNode(node *head,int value)
{
if(head==NULL)
{
head=(node *)malloc(sizeof(node));
if(head==NULL)
printf("malloc failed");
else
{
head->data=value;
head->next=NULL;
}
}
else
{
node *temp=(node *)malloc(sizeof(node));
if(temp==NULL)
printf("malloc failed");
else
{
temp->data=value;
temp->next=head;
head=temp;
}
}
return head;
}
int main(void)
{
node *t,*q,*p=NULL;
p=InsertNode(p,8);
p=InsertNode(p,7);
p=InsertNode(p,6);
p=InsertNode(p,5);
p=InsertNode(p,4);
q=p;
p=InsertNode(p,3);
p=InsertNode(p,2);
p=InsertNode(p,1);
t=p;
while(t->next) // 找到链表的尾指针
t=t->next;
t->next=q; // 将链表的尾指针指向第四个节点,这样就构成了一个环
bool flag=IsLoop(p);
if(flag)
cout<<"这个链表存在一个环"<<endl;
else
cout<<"这个链表不存在一个环"<<endl;
system("pause");
return 0;
}
相关文章推荐
- 如何判断一个单向链表是否有环路?
- 状下算法可以判断一个单向链表中是否有环
- 判断一个单向链表中是否有环
- 判断一个单向链表中是否有环
- 判断一个单向链表是否形成了环状结构
- 判断一个单向链表上是否有环
- 判断一个单向链表是否有环,算法证明
- 用c++编写一段完整代码,要求判断一个进程(例如qq.exe)是否存在,若存在,输出存在,不存在就输出不存在。
- 判断一个单向链表中是否存在环
- Linked List Cycle-- 判断一个单向链表中是否有环存在
- 判断一个单向链表中是否存在环
- 如何判断一个单向链表是否为回文链表(Palindrome Linked List)
- 判断一个单向链表中是否有环
- 判断一个单向链表是否有环和判断一个单向链表是否是循环链表
- 判断一个单向链表中是否有环
- 判断一个单向链表中是否存在环
- 判断一个单向链表是否有环
- 写一段代码,判断一个包括'{','[','(',')',']','}'的表达式是否合法(注意看样例的合法规则。) 给定一个表达式A,请返回一个bool值,代表它是否合法。
- 如何判断一个单向链表是否有环路
- 判断一个单向链表中是否存在环