判断单链表是否存在环型链表问题

来源:互联网 发布:动态域名解析软件 编辑:程序博客网 时间:2024/06/05 11:08
 
// Link.cpp : 定义控制台应用程序的入口点。//单链表#include "stdafx.h"#include <iostream>#include <complex>using namespace std;typedef struct node {int data;//节点内容node *next;//下一个节点}node;//创建单链表node *create(){node *head,*p,*q;int i=0; //单链表中数据的个数int a=-1;head=new node;//创建头节点head->next=NULL;while (1){cout<<"please input the data(input -1,quit):";cin>>a;if (-1==a) //如果输入的是-1,退出{break;}p=new node;p->data=a;p->next=NULL;//链表的最后一个指针为NULLif (++i==1) //链表只有一个元素{           //连接到head的后面head->next=p;}else{q->next=p;//连接到链表尾端}q=p;//q指向末节点}return head;}//判断是否存在回环//如果存在,start存放回环开始的节点bool IsLoop(node *head,node **start){node *p1=head;node *p2=head;if (p2==NULL || p2->next==NULL)//head为NULL或链表为空时返回false{return false;}do {p1=p1->next;       //p1走一步p2=p2->next->next; //p2走两步} while (p2!=NULL && p2->next!=NULL && p1!=p2);if (p1==p2){*start=p1; //p1为回环开始节点return true;}elsereturn false;}int _tmain(int argc, _TCHAR* argv[]){bool bLoop=false;node *head=create(); //创建单链表node *start=head->next->next->next; //使第4个节点为回环开始位置start->next=head->next; //回环连接到第2个节点node *loopStart=NULL;bLoop=IsLoop(head,&loopStart);cout<<"bLoop="<<bLoop<<endl;cout<<"start==loopStart?"<<(loopStart==start)<<endl;system("pause");delete [] head;return 0;}