写一段代码判断一个单向链表中是否有环
来源:互联网 发布:福州数据分析薪酬 编辑:程序博客网 时间:2024/06/06 07:50
#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;
}
- 写一段代码判断一个单向链表中是否有环
- 判断一个单向链表中是否有环
- 判断一个单向链表中是否有环
- 判断一个单向链表中是否有环
- 判断一个单向链表中是否有环
- 判断一个单向链表中是否有环
- 判断一个单向链表中是否有环
- 判断一个单向链表上是否有环
- 判断单向链表中是否有环
- 判断单向链表中是否有环
- 判断单向链表中是否有环
- 判断单向链表中是否有环
- 判断单向链表中是否有环
- 判断一个单向链表中是否存在环
- 判断一个单向链表中是否存在环
- 判断一个单向链表中是否存在环
- 判断一个单向链表是否有环
- 判断一个单向链表是否有环
- 软件版本 Alpha Beta Express等含义
- perl 模式匹配
- antenna简单教程
- 普适计算的网上资源
- SPI protocol 驱动编写 Part 1
- 写一段代码判断一个单向链表中是否有环
- Object C 字符串、数组、字典集合 NSString NSArray NSDictionary操作
- H264 码流结构
- setlocale
- Android开发--身高体重指数(BIM)计算--设计用户界面--视图(View)设计
- VS2010单文档
- 函数
- java面试笔试题大汇总
- 字体设计是网页设计的根本