// 判断一个单链表中是否有环.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
//定义单链表的长度
const int length = 22;
//定义单链表中环的起点
const int circularNum = 11;
struct Node
{
int value;
struct Node *next;
};
Node *createCircularLinklist(int num)
{
Node *head, *last, *p, *temp;
head = (Node *)malloc(sizeof(Node));
last = (Node *)malloc(sizeof(Node));
for(int i=0; i<length; i++)
{
p = (Node *)malloc(sizeof(Node));
p->value = i;
p->next = NULL;
if(i == 0)
head->next = p;
if(i == num)
temp = p;
last->next = p;
last = p;
}
last->next = temp; //最后一个点指向环的起点
return head->next;
}
void traverse(Node *ptr)
{
int count = 0;
while(ptr != NULL)
{
if(count>length)
break;
std::cout << ptr->value;
if(ptr->next != NULL)
std::cout << " -> ";
ptr = ptr->next;
count++;
}
std::cout<<std::endl;
}
int isCircular(Node *list)
{
bool isLoop = false;
if(list == NULL) return -1;
Node *ptr_fast,*ptr_slow;
ptr_fast = list;
ptr_slow = list;
while(ptr_fast->next && ptr_fast->next->next)
{
ptr_fast = ptr_fast->next->next;
ptr_slow = ptr_slow->next;
if(ptr_fast == ptr_slow){
isLoop = true;
std::cout<<"It's Circular!"<<" Meeting at: "<<ptr_fast->value<<std::endl;
break;
}
}
if(!isLoop){
std::cout<<"It's not Circular!"<<std::endl;
return -1;
}
int length = 0;
while(ptr_fast->next && ptr_fast->next->next){
ptr_fast = ptr_fast->next->next;
ptr_slow = ptr_slow->next;
length++;
if(ptr_fast==ptr_slow){
std::cout<<"The length: "<<length<<" Meeting at: "<<ptr_fast->value<<std::endl;
break;
}
}
ptr_fast = list;
int len = 0;
while(ptr_fast!=ptr_slow){
ptr_fast = ptr_fast->next;
ptr_slow = ptr_slow->next;
len++;
}
std::cout<<"Starting node: "<<ptr_fast->value<<std::endl;
std::cout<<"lenght of link: "<<len+length<<std::endl;
}
int main()
{
Node *list = createCircularLinklist(circularNum);
traverse(list);
isCircular(list);
return 0;
}
判断一个单链表中是否有环
最新推荐文章于 2022-05-19 22:54:00 发布